0% found this document useful (0 votes)
123 views113 pages

Java Workshop July

This document provides an overview of the Java programming language and tools for learning Java. It discusses what Java is, why we need to learn Java, and the tools required such as the JDK and IDEs. It also covers Java concepts like variables, data types, operators, methods, input/output, arrays, and basic control structures like if/else statements and loops. The document is intended to help get started with learning the Java language.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
123 views113 pages

Java Workshop July

This document provides an overview of the Java programming language and tools for learning Java. It discusses what Java is, why we need to learn Java, and the tools required such as the JDK and IDEs. It also covers Java concepts like variables, data types, operators, methods, input/output, arrays, and basic control structures like if/else statements and loops. The document is intended to help get started with learning the Java language.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 113

FastTrack to Java

Mohamed Sanaulla
Sun Campus Ambassador
Mohammed.Sanaulla@sun.com
Essential 
Classes
Learning 
th
the 
Language
Getting 
Getting
Started 
Getting Started
Getting Started

What is Java?

Why do we need 
to learn Java?

Tools required for 
learning Java
What is Java?
What is Java?
J P i Language
Java as Programming L

Object  Architectural 
Simple
Oriented Neutral

High 
High
Portable Distributed
Performance

Multithreaded Robust Dynamic


Java as a Platform
Java as a Platform
Java Virtual Machine (JVM)
Java Virtual Machine (JVM)

Interprets the Java Byte Code

Base for the Java Platform

Can be ported to any platform(OS)
Application Programming
Application Programming 
Interface (APIs)

LLarge collection of ready‐made 
ll ti f d d
software components that 
provide many useful capabilities
provide many useful capabilities. 
It is grouped into libraries of 
related classes and interfaces; 
these libraries are known as 
packages.
Why do we need to learn Java?
Tools used for Java
Tools used for Java
¾Notepad or Notepad++ or any other 
¾Notepad or Notepad++ or any other
editor
¾JDK‐ Java Development Kit‐
Java Development Kit‐ Consists of 
Consists of
Java Libraries, tools and the Virtual 
Machine
¾NetBeans IDE
¾Eclipse IDE
¾Eclipse IDE
¾Java SE Documentation
Learning the Language
Variables, Types and 
V i bl T d
Operators
p
First Program:
First Program:

Class NotHelloWorld
{
public static void main(String[] args)
{
System.out.println(“Not A Hello World Program”);
}
}

Demo Using Notepad
Program Structure

Class <Classname>
{
public static void main(String[] arguments)
{
<Statements>
}
}
Data Types
¾Strongly Typed Language
¾Sizes of all Numeric types are platform independent
¾Eight primitive types 4 integers, 2 floating points, 1 Character 
¾Eight primitive types‐ 4 integers 2 floating points 1 Character
and 1 boolean
¾Integers:
¾l
¾long‐ 8 bytes
b
¾int‐ 4 bytes
¾short‐ 2 bytes
y
¾byte‐ 1 byte
¾Floating Point:
¾float‐ 4 bytes
4 bytes
¾double‐ 8 bytes‐ More precision than float
¾char‐ 2 bytes‐It is Unsigned, Accommodates all characters used in 
all languages in the world  
ll l i h ld
¾boolean‐ 2 Values‐ false or true
Variables
¾Named Storage location
¾Named Storage location‐ Value changes during the course of program 
Value changes during the course of program
execution
¾Declare‐ Placing the type first followed by the name of variable
¾2 Types of Variables:
¾2 Types of Variables:
¾Primitives‐ Once Declared Type cannot be changed, but value can
¾Reference Variables
¾Declaring: <Variable
¾Declaring:   Variable Type
Type> <Variable
Variable Name
Name>;;
int length,width,height;
boolean status;
¾Cannot Use Java Key Words
y as Variable Names, must not begin with a digit, 
, g g ,
can be of any length, case is significant
¾Initializing: Cannot use uninitialized Local Variables
int length=23;
g ;
boolean status=true;
¾Constants‐ Declared by using “final” keyword‐ Which means variable cannot 
be assigned new value
final double length=2.54;
Operators
Assignment Operators:
4 Commonly Used: +=, ‐+, *=, /+
Relational Operators:
Relational Operators:
6 Relational Operators: <, >, <=, >=, ==, !=
Arithmetic Operators: 
B i O
Basic Operators: +, ‐, *, /, %
t * / %
Note: If either operand is a String, the + operator 
becomes a String concatenation operator. If both the 
operands are numbers, the + operator is the addition 
operator

Demo
Methods

class MethodDemo
{
public static void main(String[] args)
{
showMessage(“Sanaulla”);
}

static  void  showMessage (String name)
{
System.out.println(“Hi!!!”+name);
}
}
Input and Output
Taking Input:
import java.util.*;
Scanner in = new Scanner(System.in);
i ( i )

in.nextInt();
() //For reading Integer
g g
in.nextDouble(); //For Reading Double
in.nextLine(); //For Reading Complete Line

Output:
System.out.println( Not Hello World
System.out.println(“Not Hello World”);
);
Similar to – printf(“Not Hello World\n”);

System.out.print(
System out print(“Not
Not Hello World
Hello World”);
);
Similar to‐ printf(“Not Hello World”);
Arrays
An array is an ordered
A i d d collection
ll ti that stores
th t t many
elements of the same type within one variable name.
¾Elements are the items in an array.
¾Each element is identified with an index number.
¾Index numbers always start at 0 for the first element.
¾The length of an array is established when the array is 
created. After creation, its length is fixed.
Declaring Array:
int[] key; //Array of ints

Thread[] threads; //Array of Object References

Constructing Arrays:
i
int[] key = new int[4];

Multidimensional Arrays:
int[][] myArray=new int[3][];

Declaring, Constructing, Initializing on One Line:
int[] keys = {5,6,7,8};
S i []
String[] names ={“qwer”, “qweqe”,”gffsdf”};
{“ ”“ ”” ff df”}

Anonymous Array:
int[] testScores;
testScores=new int[]{6,7,8};
int[] testScores = new int[4];
Basic Control Structures

if … else Structure

for loop and for each loop

while loop

switch statements

d
do… while loop
hil l
if … Else Structure
class IfElseDemo
{ Input for Age
int age;
System.out.println(“Enter the Age of the person”);
Scanner in = new Scanner(System.in);
age in.nextInt();
age=in.nextInt();
Trrue  Blocck

if(age<18)
{
System.out.println(“Not eligible for Voting”);
}
else
{
Syste .out.p t ( g b e fo ot g );
System.out.println(“Eligible for Voting”);
}
} False Block
if (condition)
{
Statements to be executed
}
else if (condition)
{
Statements to be executed
}

else
{
Statements to be executed
}
One Caution!!!!!!
You Want to do this:

if( someBooleanVariable
( ==  true ))
{
Statements;
}

But End up doing this:
if(
if( someBooleanVariable
B l V i bl = true
t )
{
Statements;
}
else
{
Statements;
}
for loop
Loop Control variable
l bl L
Loop Exit Condition
E it C diti

for( int
( i=0 ; i<5  ; i++ )
; ; ) Increment/Decrement

{
for(int j=0;j<=i;j++) Nested Loop
{
System.out.print(“ “+j);
}
System.out.println();
}
Loop Body
for(initialization; termination; increment)
o ( t a at o ; te at o ; c e e t)
{
Statements;
}

Demo
Some for Loop Issues:
¾None of the three sections of the for declaration are required

for ( ; ; )  
{
Statements;
}

¾Variables declared in the for statement are local to the for loop anc
can’t be used outside the scope of the loop

for(int i=0;i<6;i++
{
System.out.println(“Hi”);
}
System out println(i); //Error
System.out.println(i);
for each loop
Also called as the Enhanced For loop, was 
added in Java 5. It simplifies looping 
through Arrays and Collections. The 
enhanced for Loop has two components.
Declaration
int[] a ={1,2,3,4,5,6};

for(  int i :  a ) Expressions

{
System.out.println(i);
}
Declaration

The newly declared block variable , of a 
The newly declared block variable of a
type compatible with the elements of the 
array you are accessing. This variable will 
you are accessing This variable will
be available within the for block, and its 
value will be the same as the current array
value will be the same as the current array 
element.
Expression

This must evaluate to the array one wants to 
loop through. This could be an array variable or 
a method call that returns an array. The array 
can be any type: primitives, objects, even arrays 
of arrays
of arrays
while loop
Expression
int x=2;

while ( x < 6 )
while (x<6)
{
System.out.println(x);
x ;
x++;
}
while ( expression )

{
//Do stuff
}

Used when the number of iterations of the 
bl k/ t t
block/statements are not known
t tk

Demo
switch statements
switch(expression)
{
case constant1: code block
case constant2: code block
default: code block
default: code block
}

Demo
Legal Expressions for switch and case:

¾A switch’s expression must evaluate to a char, byte, 
short, int.
short, int.
¾A case constant must evaluate to the same type as 
the switch expression can use
¾The case constant must be compile time constants
Compile time constant has to be resolved at compile 
ti
time, that means one can use only a constant or final 
th t l t t fi l
variable that is assigned a literal value. 
¾The switch can only check for equality. 
¾The switch can only check for equality
¾Its also illegal to have more than one case label 
using the same value
g
do … while Loop
The do loop is similar to while loop, except 
that the expression is not evaluated until 
after the do loop’s code is executed.

Demo
OO Programming Concepts

What is an Object?

What is a Class?

What is Encapsulation?

What is Inheritance?

Wh t i P l
What is Polymorphism?
hi ?
What is an Object?
Software Objects are similar to real world Objects‐
Software Objects are similar to real world Objects‐ They 
They
consists of two characteristics:
1. State
2. Behavior
h i

State ‐> Depicted by means of fields
p y
Behavior ‐> Depicted by means of methods
Advantages of Using Objects

ƒModularity: The source code for an object can 
be written and maintained independently of the
be written and maintained independently of the 
source code for other objects
ƒInformation Hiding: Using Methods for 
interacting will hide the internal implementation 
details
ƒCode Reuse:
C d R Th
The existing Object can be re used 
i ti Obj t b d
ƒPluggability and debugging ease: If a particular 
object is faulty then it can be removed or
object is faulty then it can be removed or 
corrected. Similar to Bolt in a machine
What is a class?

A class is a general specification or 
description for a set of objects  that 
defines their common structure (data), 
behavior (methods), and relationships. 
Objects are instances of Class
What is Inheritance?
•Inheritance is a relationship between classes where one 
is a relationship between classes where one
class is a parent of another. 
•Implements  “is‐a” relationship between objects
li h bj i k
•Commonality among the Objects is taken out to reduce d
complexity
•Provides the idea of reusabilityy
What is Polymorphism?

¾Ability to take more than one forms
¾Polymorphism refers to the capability of 
refers to the capability of
having methods with the same names and 
parameter types exhibit different behavior
parameter types exhibit different behavior 
depending on the receiver.
What is Encapsulation?
¾Encapsulation refers to mechanisms that allow 
each object to have its own data and methods 
i.e. wrapping up of data and methods into a 
single unit called class
¾Defining class state as private and channeling
¾Defining class state as private and channeling 
access to them through accessor and mutator
methods. 
methods.

¾Accessor Methods: Accessor methods return 


information
¾Mutator Methods: Mutator methods modify 
th t t f th bj t
the state of the object. 
End of Session‐1
d f i
Competition Session 1
Competition – Session 1
FastTrack to Java
to Java
Session‐2

Mohamed Sanaulla
Sun Campus Ambassador
Mohammed.Sanaulla@sun.com
The official website+mailing list of NITK Sun Club

http://groups.google.com/group/nitk‐sun‐club
p //g p g g /g p/

Subscribe to this Google group to register for NITK Sun Club!

¾Discussions: Feel free to post any queries, ideas, news you have to 
the mailing list / take part in the discussions.
h ili li / k i h di i

¾Files, Links, Resources: Find and share all important 
files/documents like slide presentations, documentation, tutorials, 
files/documents like slide presentations documentation tutorials
posters, brochures, etc related to the club's activities.

¾Events & Achievements: Get to know about all the latest 
happenings and upcoming events of the club.
Session‐1 Contest
Winners!!!!

Mohit Kukreja
j

Srivatsa S.Bhat
S Bhat

Ruchi Rathore
Obj O i
Object Orientation in Java
i i J
Classes
In General classes in Java are made up of three parts:
p p
1. Fields ‐ Define the state/attributes of the Class
2. Constructors ‐ Used for Initializing the Objects during 
their creation time
their creation time
3. Methods ‐ Define the Behavior of a particular class, 
also used for accessing the fields

<Access_Modifier> class <ClassName>
{

Fields

Constructor

Methods

}
A Class can be marked

public default final abstract

The “default” access level cannot by marked by using 
“default” keyword. It’s the access level by default
Member Access Modifiers
¾Members can use all four access levels: public, 
¾Members can use all four access levels: public
protected, private, default

¾Public members can be accessed by all other classes

¾Private members can be accessed by the code in the 
same class

¾Default members can be accessed only by classes in the 
same package
same package

¾Protected members can be accessed by other classes in 
the same package, plus subclasses regardless of the 
package.
Nonaccess Member Modifiers
¾Final methods‐ cannot be overridden in a subclass
¾Final variables‐
variables value cannot be changed
value cannot be changed
¾Abstract methods‐ methods declared but not 
implemented
¾Synchronized methods‐ methods can be accessed by 
only one thread at a time
¾Transient Variable‐ The variable is marked as “Transient” 
is skipped during serialization
¾V l til Variable‐
¾Volatile V i bl The thread accessing the variable uses 
Th h d i h i bl
its own private copy, with master copy in memory
Constructors
ƒConstructor
Constructor is a method that has the same
is a method that has the same name as that of the 
as that of the
class and has no return type‐ not even void. 

ƒEvery class MUST have a constructor‐ By default Java provides 


“No‐Arg” Constructor. 

ƒConstructors can use any access modifiers

ƒEvery constructor has, as its first statement, either a call to an 
overloaded constructor or to the superclass constructor.

ƒThe compiler by default insert a no‐arg call to super() as the very 


first statement in the constructor.

ƒInterfaces do not have Constructors


Objects
‰Instances of Classes
‰Instances of Classes

‰Created by using the “new”


‰Created by using the  new  keyword
keyword

‰They live on the heap area of the memory

‰They are accessed by using Object References that 


li
live on the stack
th t k

‰They are used to access the Class members namely 
‰They are used to access the Class members namely
Methods and Fields by using the “.” operator
aa              at last
DEMO at last
DEMO 
Static Variables

Static Methods
Static Fields

¾Defined by using the keyword “static”.

¾There’s only one such field per class which 
means that all objects share a common copy.
means that all objects share a common copy.

¾Static constants are more popular

¾“public static final” is used to define a 
constant. 
Static Methods

¾They do not operate on objects i.e. they don
¾They do not operate on objects i.e. they don’tt 
have a “this” parameter.

¾Cannot access instance variables but can 
access only static variables.

¾They are accessed by using the name of the 
class though it is legal to use the object to
class, though it is legal to use the object to 
access the static method. 
DEMO: Using Static Variables 
DEMO: Using Static Variables
and static methods
and static methods
Initialization Blocks
Apart from Constructors and methods, initialization blocks  are the 
A f C d h d i i i li i bl k h
only place where Java operations can be performed. There are two 
types of Initialization blocks in Java:

¾Instance Initialization Blocks ‐ They run once every time the new 
instance is created
instance is created.

¾Static Initialization Blocks ‐ They run once, when the class is first 
l d d D fi d b
loaded. Defined by using the keyword “static”.
i th k d “ t ti ”

Some Rules to remember:
¾Init Blocks execute in the order they appear.
¾Static Init Blocks run once, when the class is first loaded.
¾Instance Init blocks run every time a class instance is created
¾Instance Init blocks run every time a class instance is created
¾Instance Init blocks run after the constructor’s call to super().
DEMO: Using Initialization Blocks
Method overloading
Overloaded methods lets one to reuse the same method 
name in a class, but with different arguments.

The rules for Overloading are:
ƒOverloaded
Overloaded methods MUST change
methods MUST change the argument list.
list
ƒOverloaded methods CAN change the return type.
ƒOverloaded methods CAN change the access modifier.
ƒOverloaded methods CAN declare new or broader 
checked exceptions

DEMO: Using Overloaded Methods
Inner Classes
Inner Class is a class defined inside another class.
Why use Inner Classes?
•Can access the data from the scope in which they are defined
•Can be hidden from the classes in the same package
•Reduce the amount of coding involved

Inner Classes come in 4 flavors:
1. Static Member Classes ‐
b l Marked with static, cannot access non static 
k d h
members of top level class., not an inner class‐ Top Level Nested class

2 Member
2. Member Classes
Classes ‐ It
It’ss a class that is member of another class, to instantiate 
a class that is member of another class to instantiate
an inner class one has to have an instance of outer class
MyOuter.MyInner inner = (new MyOuter()).new MyInner();

3 Local Classes ‐
3. l Cl Defined within a method of the class, only final and abstract 
fi d i hi h d f h l l fi l d b
can be applied, local variables cannot be accessed.

4 Anonymous
4. Anonymous Classes ‐
Classes No name, either they extend a class or implement an 
No name either they extend a class or implement an
interface
DEMO: Using Anonymous Inner Classes
DEMO: Using Anonymous Inner Classes

DEMO: Using Local Classes
Inheritance

¾Inheritance in java is done using the keyword 
“extends”.
“extends”
¾A class that is derived from another class is called 
a “subclass”.
a  subclass .
¾The class from which the subclass is derived is 
called a “superclass”.
¾Every Class extends from the class “Object”.
¾Multiple Inheritance in Java is not possible, but 
then there’s another way of doing it.
h h ’ h fd i i
IS‐A and HAS‐A relationship

IS‐A Relationship is associated with 
p
Inheritance. Suppose MySubClass
extends/inherits MySuperClass then 
MySubClass IS‐A MySuperClass

HAS‐A Relationship is based on Usage
rather than inheritance. Suppose class A 
HAS‐A class B if code in class A has a 
reference to an instance of class B.
Method Overriding
¾Can override the method inherited from the Super 
Class unless it is marked “final”. 
¾U d d fi b h i
¾Used to define behavior specific to the sub class.
ifi h b l
¾The argument list must exactly match that of the 
overridden method
overridden method
¾The return type must be the same as or a subtype of 
the return type declared in the original overridden 
yp g
method.
¾Access level can’t be more restrictive.
¾Static methods can’t be overridden‐ They are 
actually hidden.

DEMO: Using Method Overriding
Interfaces
¾An interface is a reference type, similar to a class, that can contain 
only constants, method signatures, and nested types.

¾They can be implemented
y p unlike concrete classes that can be 
extended

¾They help in providing Java type of Multiple Inheritance.


¾They help in providing Java type of Multiple Inheritance

¾ All interface methods are implicitly public and abstract. One can use 
any combination of public or abstract or no modifiers.

¾All variable defined in the interface must be public, static
p , and final. 
Any combination of public, static, final or no modifiers is legal.

¾An interface can extend one or more interfaces


¾An interface can extend one or more interfaces.

DEMO: Using Interfaces
Garbage Collection
ƒAutomated Memory Management‐
ƒAutomated Memory Management Delete Objects that can’t be reached
Delete Objects that can’t be reached
ƒCan only Suggest VM for GC
ƒNo particular GC Algorithm can be known for sure
ƒObjects must have live, reachable reference
Obj t th li h bl f
Making Objects eligible for GC:
Nulling a Reference: 
MyClass
l obj
bj = new MyClass();
l ()
obj=null;
Reassiging Reference Variable:
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1 = obj2;
Isolating a Reference‐ Islands of Isolation

Forcing GC‐ Contradiction‐ Cannot be forced but suggested


System.gc();
•finalize()‐ Run code b4 GC, called only once in an Object’s life time.
Numbers and Strings

Numbers
b Strings
Strings
ƒString objects are immutable but String reference variables 
are not

ƒString class is Final‐ Methods can’t be overridden.

ƒJVM finds a String literal‐ Its added to String Constant Pool

ƒIf a String is not assigned a reference it can be lost


ƒIf a String is not assigned a reference, it can be lost

DEMO: Using Strings
Numbers
ƒint, byte,  float ‐> Primitives , but Java is OO Language

ƒWrappers
Wrappers are provided for each primitive which wrap the 
are provided for each primitive which wrap the
primitives into Objects
Why?
‐ Enable handling like Objects
Enable handling like Objects
‐ Classes provide utility methods for primitives

ƒAutoboxing ‐> Automatically converts primitive into wrapper


Objects and vice versa

ƒWrappers are equal (equals()) ‐> Same type and have Same value

ƒCharacter and Boolean wrappers comes in java.lang, others come 
ƒCharacter and Boolean wrappers comes in java lang others come
under java.lang.Number
In summary, the essential method signatures for Wrapper 
conversion methods are
conversion methods are
primitive xxxValue() ‐ to convert a Wrapper to a 
Ex: byteValue()
Ex: byteValue() primitive
primitive parseXxx (String) ‐ to convert a String to a primitive
Ex: parseInt()
p ()
Wrapper valueOf(String) ‐ to convert a String to a Wrapper
Method 
s = static
n = NFE exception Boolean  Byte  Character  Double  Float  Integer  Long  Short 
byteValue x  x  x  x  x  x 
doubleValue x  x  x  x  x  x 

floatValue x  x  x  x  x  x 
intValue xx  xx  xx  xx  xx  xx 
longValue x  x  x  x  x  x 
shortValue x  x  x  x  x  x 

parseXxx s,n x  x  x  x  x  x 
parseXxx s,n x  x  x  x 
(with radix)

valueOf s,n x  x  x  x  x  x  x 
valueOf s,n x  x  x  x 
(with radix)
(with radix)

toString x  x  x  x  x  x  x  x 
toString s x  x  x  x  x  x  x  x 
(primitive)
toString s x  x 
(primitive, 
radix)
Passing Variables into Methods
ƒJava is always Pass by Value 

ƒWhile passing Local Variables‐ Its resembles Pass by 


Value

ƒWhile passing Reference Variables‐ Its resembles Pass 
By Reference, But its pass by Value

DEMO: Passing Object Reference Variables

DEMO: Passing Local Variables
The StringBuilder Class
¾StringBuilder objects are like String
objects are like String objects but then they are 
objects but then they are
mutable i.e the value they are referring to can be changed

¾Instances of StringBuilder
¾I t f St i B ild are not safe for use by multiple 
t f f b lti l
threads i.e the methods are not synchronized

¾StringBuilders‐ simpler code and better performance

¾Appending strings becomes time
¾Appending strings becomes time and memory
and memory efficient
efficient‐ Cause 
Cause
the String involves new memory allocation and string relocation.

¾APIs of StringBuffer
¾API f St i B ff and StringBuilder
d St i B ild are same‐ StringBuilder
St i B ild
was introduced in JDK 5.0

DEMO: Using StringBuilder
Using JDK Documentation
End of Session‐2
d f i
Competition Session 2
Competition – Session 2
FastTrack to Java
to Java
Session‐3

Mohamed Sanaulla
Sun Campus Ambassador
Mohammed.Sanaulla@sun.com
Essential Classes
Exception Handling
9Exception handling ‐> Elegant Mechanism for Handling 
Exception

9Separates Exception Generating and Exception Handling
codes

9Exception – Alters the normal program flow.

9try and catch keywords used for Exception Handling 


Mechanism

9try ‐> Defining Block of code where exceptions can occur

9catch ‐> Defining Block of code that handles a specific 


exception
try
{
//Risky Code Goes here that causes some kind of exception
}
catch(MyFirstException)
{
//Handle this Exception
//Handle this Exception
}
catch(MySecondException)
{
//Handle this Exception
}
// Normal Non Risky code continues here

Note: The “catch”


Note: The  catch blocks Immediately
blocks Immediately follow the 
the “try”
try  block
block
Using finally
9Different from “finalize”

9Code inside the “finally” block is executed at some point after try 
block – Whether an exception is thrown or not

9If there’s a “return” statement‐ Its is executed immediately after 
th “ t ” i
the “return” is encountered but before the “return” executes.
t db tb f th “ t ” t

9If No Exceptions‐ It is executed immediately after try block

9If there’s Exceptions‐ It is executed after the “catch” block

9tryy without a catch but with finallyy is legal


g
9try without a catch and also finally is illegal
9try with catch and finally is legal.

DEMO: Using Exception Handling
Exception Hierarchy
Basic I/O
Important I/O Classes:
‰File ‐> An abstract representations of file and directory 
path name.
h

‰FileReader ‐> Used to read Character Files

‰BufferedReader ‐> Wrap around the Low Level readers‐
Read large chunks of data from file and store it in buffer‐
Read large chunks of data from file and store it in buffer‐
Reduces the No of Read Operations

‰Fil W i ‐> Used to write to character files.
‰FileWriter U d i h fil

‰Buffered Writer ‐> Wrap around the low level writers

import  java.io.*; ‐> To be used
Using class “File”

A new instance of class File does not mean 
making an actual file its just creating a file
making an actual file, its just creating a file 
name

DEMO
Some Methods Used:
ƒboolean exists() ‐> returns “true” if it can find 
the actual file

ƒboolean createNewFile() ‐> Creates a new file
createNewFile() > Creates a new file
Using FileReader and FileWriter

‐> Most of the time they are used with wrapping them i.e
by using it along with PrintWriter and PrintReader. Its 
also called as chaining

DEMO

DEMO: Using PrintWriter
java.io Class  Extends From  Key Constructor(s)  Key Methods 
Arguments 
File  Object  File, String  createNewFile() 
St i
String  d l t ()
delete() 
String, String  exists() 
isDirectory() 
isFile() 
li t()
list() 
mkdir() 
renameTo() 
FileWriter Writer  File  close() 
String  flush() 
write() 
BufferedWriter Writer  Writer  close() 
flush() 
flush()
newLine() 
write() 
PrintWriter Writer  File (as of Java 5)  close() 
String (as of Java 5)
String (as of Java 5)  flush()
flush() 
OutputStream format()*, printf()* 
Writer  print(), println() 
write() 
Fil R d
FileReader R d
Reader  File 
Fil read() 
d()
String 
BufferedReader Reader  Reader  read() 
readLine() 
Serialization
ƒUsed for Saving the State (Instance Variables) of one or more 
Objects

ƒVariables marked “transient” cannot be saved during object 
“Serialization”

ƒBasic Serialization involves only two methods‐
• Serialize the objects and write them to the stream
j
• Read the stream and deserialize the objects

ObjectOutputStream writeObject()
ObjectOutputStream.writeObject()

ObjectOutputStream.readObject()

DEMO:  Using Serialization
DEMO: Using Serialization for Saving 
DEMO: Using Serialization for Saving
Object Graphs
Multithreading
ƒIn Java, “thread” means‐
ƒAn instance of class.java.lang.Thread
j g
ƒA thread of execution

ƒA thread of execution is an individual process that has 
h d f d d l h h
its own call stack.

ƒJVM acts like a mini –OS ‐> Schedules its own threads

ƒThe programs must not be designed dependent on 
particular implementation of the JVM.
Making a Thread
ƒI t
ƒInstance of java.lang.Thread
fj l Th d

ƒImportant Methods:
ƒ start()
ƒ yield()
ƒ sleep()
ƒ run()

ƒThe actual action or the job code is written in “run()”


ƒThe actual action or the job code is written in “run()”

ƒThe thread of execution always begins with the run() 
method

ƒThread
Thread can be defined and Instantiated in 2 ways:
can be defined and Instantiated in 2 ways:
ƒ Extend the java.lang.Thread class
ƒ Implement the Runnable Interface
Defining a Thread:
By Extending the java.lang.Thread
d h l h d class:
l

class MyThread extends Thread


{
public void run()
{
System.out.println(“Job Running in
MyThread”);
}
}

The thread with run() method will be executed as the starting for thread.
() g

Implementing java.lang.Runnable:

class MyRunnable implements Runnable


{
public void run()
{
System out println(“Job
System.out.println( Job Running in
MyRunnable”);
}
}
Instantiating a Thread:
ƒOne has to have Thread object to run the thread‐
ƒO h t h Th d bj t t th th d Regardless of subclassing
R dl f b l i or 
implementing

ƒIf the Thread class is extended then‐

MyThread t = new MyThread();

ƒIf
If the Runnable
the Runnable is implemented then
is implemented then‐

MyRunnable r = new MyRunnable();


Thread t =new Thread(r); //Passing Runnable to Thread

ƒThe  same job can be given to multiple threads
public class TestThreads
{
public static void main(String[] args)
{
MyRunnable r =new MyRunnable();
Thread foo = new Thread(r);
Thread bar= new Thread(r);
Thread bat = new Thread(r);
}
}
Starting a Thread:

To start executing a thread‐ start() Method is used
t.start();

After calling start():
A new Thread of execution starts
Thread moves from new state to Runnable state
run() method is ready to run

DEMO: Starting and running a Thread
Starting and Running Multiple Threads:

DEMO: Starting and Running Multiple Threads
g g p

ƒThe
The order threads executing cannot be guaranteed
order threads executing cannot be guaranteed‐ The only 
The only
Guaranteed thing is‐
Each thread will start and each thread will run to 
completion
Thread States

The Different thread states are:
ƒNew
ƒRunnable
ƒRunning
ƒWaiting/blocked/sleeping
Sun Club ‐ NITK

Sun Club‐ Google Group:


Sun Club Google Group:
http://groups.google.com/group/nitk‐sun‐club

Official Blog:
http://sunclubatnitk.wordpress.com/
My Java Blog:
http://javaforyou wordpress com/
http://javaforyou.wordpress.com/
The official website+mailing list of NITK Sun Club

http://groups.google.com/group/nitk‐sun‐club
p //g p g g /g p/

Subscribe to this Google group to register for NITK Sun Club!

¾Discussions: Feel free to post any queries, ideas, news you have to 
the mailing list / take part in the discussions.
h ili li / k i h di i

¾Files, Links, Resources: Find and share all important 
files/documents like slide presentations, documentation, tutorials, 
files/documents like slide presentations documentation tutorials
posters, brochures, etc related to the club's activities.

¾Events & Achievements: Get to know about all the latest 
happenings and upcoming events of the club.

You might also like