SlideShare a Scribd company logo
UNIT-1, 2
JAVA
TECHNOLOGIES
SYLLABUS
Unit - I
Concept of OOPS, History of Java, how Java works, Java Virtual Machine(JVM),
Java In Time(JIT) compiler, Java features, Java application types. Data types,
Operators, If Statements, Switch Statement, Loops, Arrays, casting, command
line arguments.
UNIT II
Java Classes and Memory Management
Introduction to Classes, objects, Constructors, inheritance (Single, Multilevel,
Hybrid), Abstraction, encapsulation, polymorphism, finalizes, garbage
collection, access specifier, Java interface, Packages.
History of Java
⚫ Java started out as a research project.
⚫ Research began in 1991 as the Green Project at
Sun Microsystems, Inc.
⚫ Research efforts birthed a new language, OAK. ( A tree
outside of the window of James Gosling’s office at Sun).
⚫It was developed as an embedded programming language,
which would enable embedded system application.
⚫It was not really created as web programming language.
⚫Java is available as jdk and it is an open source s/w.
History of Java (contd…)
Language was created with 5 main goals:
 It should be object oriented.
 A single representation of a program could be executed on
multiple operating systems. (i.e. write once, run anywhere)
 It should fully support network programming.
 It should execute code from remote sources securely.
 It should be easy to use.
⚫ Oak was renamed Java in 1994.
⚫Now Sun Microsystems is a subsidiary of Oracle
Corporation.
James Gosling
Green Team
Java
Logo
Versions of Java
Version Codename Year Features Added
JDK 1.0 Oak Jan23,1996 -
JDK 1.1
Rebirth of
Java
Feb19,1997
Inner classes JavaBeans, JDBC, RMI, Reflection, AWT.
J2SE 1.2 Playground Dec8, 1998
JIT compiler, Collections, IDL & CORBA, strictfp, Java
Plug-in.
J2SE 1.3 Kestrel May8, 2000
HotSpot JVM, JavaSound, Java Naming and Directory
Interface, Java Platform Debugger Architecture.
J2SE 1.4 Merlin Feb6, 2002
Preferences API, Logging API, assert, image I/O API,
security and cryptography extensions.
J2SE 5.0 Tiger Sep30, 2004
Generics, annotations, Autoboxing, Enumerations, Varargs,
Enhanced for each.
JA
VA SE 6 Mustang Dec11, 2006
JDBC 4.0, JVM improvements, Improved JAXB, Improved
web services, Support for older Win9x versions dropped.
JA
VA SE 7
Dolphin July28, 2011
Major updates to Java
JA
VA SE 8 - 2012 -
Java Platforms
There are three main platforms for Java:
⚫Java SE (Java Platform, Standard Edition) – runs on
desktops and laptops.
⚫Java ME (Java Platform, Micro Edition) – runs on
mobile devices such as cell phones.
⚫Java EE (Java Platform, Enterprise Edition) – runs on
servers.
Java Development Kit:
It contains one (or more) JRE's along with the various
development tools like the Java source compilers, bundling and
deployment tools, debuggers, development libraries, etc.
Java Virtual Machine:
An abstract machine architecture specified by the Java Virtual
Machine Specification.
It interprets the byte code into the machine code depending
upon the underlying OS and hardware combination. JVM is
platform dependent. (It uses the class libraries, and other
supporting files provided in JRE)
Java Terminology
Java Runtime Environment:
A runtime environment which implements Java Virtual
Machine, and provides all class libraries and other
facilities necessary to execute Java programs. This is the
software on your computer that actually runs Java
programs.
JRE = JVM + Java Packages Classes (like util,
math, lang, awt, swing etc) +runtime libraries.
Java Terminology (contd…)
Java
Source
Java
Byte codes
Java
Byte
codes
move
locally
or
through
n/w
Java
Compiler
Class Loader
Byte Code
Verifier
Java Class
Libraries
Java
Interpreter
Just-in-time
Compiler
Run Time System
Java OS Win 32 Solaris
MAC Others
Hardware
Java Execution Procedure
The Architecture of the Java Virtual
Machine
Java Virtual Machine
⚫Class loader subsystem: A mechanism for loading
types (classes and interfaces) given fully qualified
names.
⚫The Java virtual machine organizes the memory it
needs to execute a program into several runtime data
areas.
⚫Each Java virtual machine also has an execution
engine: a mechanism responsible for executing the
instructions contained in the methods of loaded
classes.
Object Oriented Programming
Concepts
⚫Objects
⚫Classes
⚫Data abstraction and
Encapsulation
⚫Inheritance
⚫Polymorphism
⚫Dynamic Binding
A class is collection of objects of similar type or it is a template.
Ex: fruit mango;
class object
Objects are instances of the type class.
The wrapping up of data and functions into a single unit ( called class) is
known
as encapsulation. Data encapsulation is the most striking features of a class.
Abstraction refers to the act of representing essential features without
including the background details or explanations
Inheritance is the process by which objects of one class acquire the
properties of another class. The concept of inheritance provides the
reusability.
Polymorphism:
It allows the single method to perform different actions based on the
parameters.
Dynamic Binding: When a method is called within a program, it
associated with the program at run time rather than at compile time is
called dynamic binding.
Java Technologies notes of unit 1 and 2.
Java Technologies notes of unit 1 and 2.
C++ JA
V
A
C++ supports pointers Java does not pointers
C++ run and compile using compiler which
converts source code into machine level
languages so c++ is plate from dependents
At compilation time Java Source code converts
into byte code .The interpreter execute this
byte code at run time and gives output .Java is
interpreted for the most part and hence
platform independent
c++ is depends upon operating system machine
etc
Java is platform independent language
c++ their is only compiler Java uses compiler and interpreter both
C++ supports operator overloading java does not.
Thread support is not available in Java Thread support is built-in Java
Internet support does not exist Internet support is built-in Java but not in C++.
Java does not support header file, include library
files just like C++ .
Java use import to include different Classes and
methods.
Goto statement exist in C++ There is no goto statement in Java.
operator overloading exist in c++. Java has method overloading, but no operator
overloading just like c++.
C++ support unsigned integer. Java does not support unsigned integer.
Features of Java
 Simple
 Object Oriented
 Compile, Interpreted and High Performance
 Portable
 Reliable
 Secure
 Multithreaded
 Dynamic
 Distributed
 Architecture-Neutral
Java
Features
⚫ Simple
⚫No pointers
⚫Automatic garbage collection
⚫Rich pre-defined class library
⚫ Object Oriented
⚫Focus on the data (objects) and methods manipulating the data
⚫All methods are associated with objects
⚫Potentially better code organization and reuse
⚫Compile, Interpreted and High Performance
⚫Java compiler generate byte-codes, not native machine code
⚫The compiled byte-codes are platform-independent
⚫Java byte codes are translated on the fly to machine
readable instructions in runtime (Java Virtual Machine)
⚫Easy to translate directly into native machine code by using
a just-in-time compiler.
⚫Portable
⚫Same application runs on all platforms
⚫The sizes of the primitive data types are always the
same
⚫The libraries define portable interfaces
Java
Features
Java
Features
⚫Reliable/Robust
⚫Extensive compile-time and runtime error checking
⚫No pointers but real arrays. Memory corruptions
or unauthorized memory accesses are impossible
⚫Automatic garbage collection tracks objects usage over
time
⚫Secure
⚫Java’s robustness features makes java secure.
⚫Access restrictions are forced (private, public)
Java Features
⚫Multithreaded
⚫It supports multithreaded programming.
⚫Need not wait for the application to finish one task before
beginning another one.
⚫Dynamic
⚫Libraries can freely add new methods and instance
variables without any effect on their clients
⚫Interfaces promote flexibility and reusability in code by
specifying a set of methods an object can perform, but
leaves open how these methods should be implemented .
Java Features
⚫Distributed
⚫Java is designed for the distributed environment of
the Internet, because it handles TCP/IP protocols.
⚫ Allows objects on two different computers to
execute procedures remotely by using package called
Remote Method Invocation (RMI).
⚫Architecture-Neutral
⚫Goal of java designers is “write once; run
anywhere, any time, forever.”
Data Types
Simple Type User Defined
Type
Numeric
Type
Non-
Numeric
clas
s
Interface
Intege
r
Floa
t
Char Boolean
floa
t
doubl
e
byt
e
shor
t
int
long
Derived Type
E.g: Array,
String…
Data Types
⚫Java Is a Strongly Typed Language
⚫ Every variable has a type, every expression has a type, and every
type is strictly defined.
⚫ All assignments, whether explicit or via parameter passing in method
calls, are checked for type compatibility.
⚫ There are no automatic conversions of conflicting types as in
some languages.
⚫ For example, in C/C++ you can assign a floating-point
value to an
integer. In Java, you cannot.
Integer Data
Types
 Java does not support unsigned, positive-only integers.
 All are signed, positive and negative values.
Byte Data Type
 The smallest integer type is byte.
 Variables of type byte are especially useful while working with a stream of
data
from a network or file.
 Byte variables are declared by use of the byte keyword.
Ex: byte b, c;
Floating Point Types
 There are two kinds of floating-point types.
 All math functions, such as sin( ), cos( ), and
sqrt( ), return double
values.
Boolean DataType
 It can have only one of two possible values, true
or false.
Character Data Type
 char in Java is not the same as char in C or C++.
 Java uses Unicode to represent characters.
 Unicode defines a fully international character set that can represent all of
the characters found in all human languages.
 It is a unification of dozens of character sets, such as Latin, Greek,
Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more.
 Hence it requires 16 bits.
 The range of a char in java is 0 to 65,536.
 There are no negative chars.
Data Types
Width in bits Range
Name
long 64 –9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038
char 16 0 to 65,536.
public class IntDemo{
public static void main(String args[]){
System.out.println(" For an Integer ");
System.out.println("Size is : "+Integer.SIZE);
int i1 = Integer.MAX_VALUE;
int i2 = Integer.MIN_VALUE ;
System.out.println("Max value is : "+i1);
System.out.println("Min Value is : "+i2);
System.out.println(" For an Byte");
System.out.println("Size is : "+Byte.SIZE);
byte b1 = Byte.MAX_VALUE;
byte b2 = Byte.MIN_VALUE ;
System.out.println("Max value is : "+b1);
System.out.println("Min Value is : "+b2);
System.out.println(" For an Short");
System.out.println("Size is : "+Short.SIZE);
short s1 = Short.MAX_VALUE;
short s2 = Short.MIN_VALUE ;
System.out.println("Max value is : "+s1);
System.out.println("Min Value is : "+s2);
System.out.println(" For an Long");
System.out.println("Size is : "+Long.SIZE);
long l1 = Long.MAX_VALUE;
long l2 = Long.MIN_VALUE ;
System.out.println("Max value is : "+l1);
System.out.println("Min Value is : "+l2);
}
}
public class FloatDemo{
public static void main(String args[]){
System.out.println(" For an Float");
System.out.println("Size is : "+Float.SIZE);
float f1 = Float.MAX_VALUE;
float f2 = Float.MIN_VALUE ;
System.out.println("Max value is : "+f1);
System.out.println("Min Value is : "+f2);
System.out.println(" For an Double");
System.out.println("Size is :
"+Double.SIZE);
double d1 = Double.MAX_VALUE;
double d2 = Double.MIN_VALUE ;
System.out.println("Max value is : "+d1);
System.out.println("Min Value is : "+d2);
}
}
public class CharDemo{
public static void main(String args[]){
System.out.println(" For a Char");
System.out.println("Size is :
"+Character.SIZE);
int f1 = Character.MAX_VALUE;
long f2 =
Character.MIN_VALUE ;
System.out.println("Max value is :
"+f1); System.out.println("Min Value
is : "+f2);
}
Variables
 The variable is the basic unit of storage in a Java program.
 A variable is defined by the combination of an identifier, a type,
and an optional initializer.
Declaring a Variable
 In Java, all variables must be declared before they can be
used.
type identifier [ = value][, identifier [= value] ...] ;
Types
 Instance Variable
 Class Variable
 Local Variable
 Parameters
Local variables :
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or
block is entered and the variable will be destroyed once it exits
the method, constructor or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared
method, constructor or block.
• There is no default value for local variables so local variables
should be declared and an initial value should be assigned
before the first use.
Instance variables :
• Instance variables are declared in a class, but outside a method,
constructor or any block.
• Instance variables are created when an object is created with the use of
the key word 'new' and destroyed when the object is destroyed.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block
in the class.
• Instance variables have default values.
• Instance variables can be accessed directly by calling the variable name
inside the class.
• However within static methods and different class ( when instance
variables are given accessibility) that should be called using the fully
qualified name ObjectReference.VariableName
Class/Static variables :
• Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
• Static variables are stored in static memory.
• Static variables are created when the program starts and destroyed when
the program stops.
• Visibility is similar to instance variables.
• Default values are same as instance variables.
• Static variables can be accessed by calling with the class name
ClassName.VariableName
class
Variables{ i
nt i;
public int j
static long l=10;
public static float f;
char c;
boolean b;
void display(int a){
i=a;
System.out.println(
"i value in
display:
"+i);
}
public static void
main(String args[])
{
double d=0.0;
//public double d=0.0; invalid
Variables v1=new Variables();
Variables v2=new Variables();
System.out.println("i value is:
"+v1.i); System.out.println("i value
is: "+v2.i); System.out.println("i
value is: "+v3.i);
System.out.println("i value is:
"+v1.j); v1.l=20;
v2.l=30;
v3.l=40;
System.out.println("l value is:
"+v1.l); System.out.println("l value
is: "+v2.l); System.out.println("l
value is: "+v3.l);
System.out.println("f value is: "+f);
System.out.println("c value is: "+v1.c);
System.out.println("b value is:
"+v1.b);
System.out.println("d value is: "+d);
}
}
class Variables{
int i;//instance variable
public int j ;//instance variable
static long l=10;//class variable
public static float f;//class variable
char c;//instance variable
boolean b;//instance variable
void display(int a){
i=a;
System.out.println("i
value in display:
"+i);
}
public static void
main(String args[]){
double d=0.0;//local
varible
//public double d=0.0; invalid
Variables v1=new Variables();
Variables v2=new Variables();
Variables v3=new Variables();
v1.display(100);
System.out.println("i value is:
"+v1.i); System.out.println("i value
is: "+v2.i); System.out.println("i
value is: "+v3.i);
System.out.println("i value is:
"+v1.j); v1.l=20;
v2.l=30;
v3.l=40;
System.out.println("l value is:
"+v1.l); System.out.println("l value
is: "+v2.l); System.out.println("l
value is: "+v3.l);
System.out.println("f value is: "+f);
System.out.println("c value is: "+v1.c);
System.out.println("b value is:
"+v1.b);
System.out.println("d value is: "+d);
}
}
Sample Program
class HelloWorld {
public static void main (String args []) {
System.out.println (“Welcome to Java Programming…..”);
}
}
public allows the program to control the visibility of class
members.When a class member is preceded by public, then
that member may be accessed by code outside the class in
which it is declared. In this case, main ( ) must be declared as
public, since it must be called by code outside of its class
when the program is started.
static allows main( ) to be called without having to instantiate
a particular instance of the class.This is necessary since main
( ) is called by the Java interpreter before any objects are
made.
void states that the main method will not return any value.
main() is called when a Java application begins. In order to
run a class, the class must have a main method.
string args[] declares a parameter named args, which is an array
of String. In this case, args receives any command-line arguments
present when the program is executed.
System is a class which is present in java.lang package.
out is a static field present in system class which returns a
PrintStream object. As out is a static field it can call directly
with classname.
println() is a method which present in PrintStream class
which can call through the PrintStream object return by static
field out present in System class to print a line to console.
class sample{
public static void main(String args[]){
System.out.println("sample:main"
); sample s=new sample();
s.display();
}
void display(){
System.out.println("display:main");
}
}
The Scope and Lifetime of Variables
Scope
The scope of a declared element is the portion of the program where
the element is visible.
Lifetime
The lifetime of a declared element is the period of time during which it
is alive.
The lifetime of the variable can be determined by looking at the context
in
which they're defined.
 Java allows variables to be declared within any block.
 A block begins with an opening curly brace and ends by a closing curly
brace.
⚫ Variables declared inside a scope are not accessible to code
outside.
⚫ Scopes can be nested. The outer scope encloses the
inner scope.
⚫ Variables declared in the outer scope are visible to the
inner
scope.
⚫ Variables declared in the inner scope are not visible to the
outside scope.
public class Scope
{
public static void main(String args[]){
int x; //know to all code within
main x=10;
if(x==10){ // starts new scope
int y=20; //Known only to
this block
//x and y both known here
System.out.println("x and y: "+x+" "+y);
x=y+2;
}
// y=100; // error ! y not known here
//x is still known here
System.out.println("x is "+x);
}
}
Operators
⚫Arithmetic Operators
⚫Bitwise Operators
⚫Relational Operators
⚫Boolean Logical
Operators
Arithmetic Operators(1)
Operator Result
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
Arithmetic Operators(2)
Operator Result
++ Increment
+= Addition assignment
– = Subtraction assignment
*= Multiplication
assignment
/ = Division assignment
%= Modulus assignment
– – Decrement
Example
:
class IncDec{
public static void main(String
args[]){ int a = 1;
int b = 2;
int c,d;
c = ++b;
d = a+
+;
c++;
System.out.println("a = " + a);
System.out.println("b = " +
b); System.out.println("c = "
+ c);
System.out.println("d = " + d);
}
}
class OpEquals{
public static void main(String
args[]){ int a = 1;
int b = 2;
int c =
3;
a += 5;
b *= 4;
c += a *
b; c %=
6;
System.out.
println("a
= " + a);
System.out.println("b = " +
b); System.out.println("c = "
+ c);
Bitwise Operators(1)
 bitwise operators can be applied to the integer types,
long, int, short, byte and char.
 These operators act upon the individual bits of their
operands.
Operato
r
~
&
|
^
>>
>>>
<<
Result
Bitwise unary
NOT Bitwise
AND Bitwise
OR
Bitwise exclusive
OR Shift right
Shift right zero fill
Shift left
Bitwise Operators(2)
Operator Result
&= Bitwise AND assignment
| = Bitwise OR assignment
^= Bitwise exclusive OR
assignment
>>= Shift right assignment
>>>= Shift right zero fill
assignment
<<= Shift left assignment
0010101
0
&0000111
1
42
15
0000101
0
10
0010101
0
^00001111
42
15
0010010
1
37
int a = 32;
a = a >> 2; 8
int a = 64;
a = a << 2; 256
–8
1111100
0
>>1
1111110
0
–4
–1
11111111 11111111 11111111 11111111
>>>24
00000000 00000000 00000000 11111111 255
Relational Operators
 The relational operators determine the relationship that
one operand has to the other.
 They determine equality and ordering.
Operato
r
==
!=
>
<
>=
<=
Result
Equal to
Not equal
to Greater
than Less
than
Greater than or
equal to Less than or
equal to
Example
:
public class
RelationalOperatorsDemo
{
public static void main(String args[])
{
int x=10,y=5;
System.out.println(“x>y:”+
(x>y));
System.out.println(“x<y:”+(x<y));
System.out.println(“x>=y:”+
(x>=y));
System.out.println(“x<=y:”+
(x<=y));
System.out.println(“x==y:”+
(x==y)); System.out.println(“x!
=y:”+(x!=y));
}
}
Boolean Logical Operators(1)
 The Boolean logical operators operate only on boolean operands.
 All of the binary logical operators combine two boolean values
to form a resultant boolean value.
Operator Result
&
|
^
| |
&
&
!
Logical
AND
Logical OR
Logical XOR (exclusive
OR) Short-circuit OR
Short-circuit AND
Logical unary NOT
& //executes both left and right side operands
&& // Java will not bother to evaluate the right-
hand operand when the outcome of the
expression can be determined by the left operand
alone.
class Test{
public static void main(String args[]){
int denom=0,num=20;
if (denom != 0 && num / denom > 10)
System.out.println("Hi");
}
}
Boolean Logical Operators(2)
Operator Result
&= AND assignment
| = OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-
else
Java Technologies notes of unit 1 and 2.
public class TernaryOperatorDemo
{
public static void main(String
args[])
{
int
x=10,y=12;
int z;
z= x > y ? x :
y;
System.out.pri
ntln(“Z=“+z);
}
Operator Precedence
Expressions
⚫An expression is a combination of constants (like 10),
operators ( like +), variables(section of memory) and
parentheses ( like “(” and “)” ) used to calculate a
value.
Ex1
:
Ex2
:
Ex3
:
x = 1;
y = 100 + x;
x = (32 - y) / (x +
5)
Control Statements
if &
switch
⚫Selection
Statements:
⚫Iteration
Statements:
⚫Jump Statements:
for, while and do-while
break, continue and
return
Selection Statements
if (condition)
statement1;
else
statement2;
if(condition)
statement;
else
if(condition)
statement;
else if(condition)
statement;
...
else
statement;
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
…
case valueN:
// statement sequence
break;
default:
// default statement
sequence
}
The condition is any expression that returns a boolean value.
The expression must be of type byte, short, int, or char;
Each of the values specified in the case statements must be of a type
compatible with the expression.
Iteration Statements
while(condition)
{
/ / body of
loop
}
d
o
{/ / body of loop
} while
(condition);
for(initialization; condition;
iteration)
{
/ / body
}
Jump Statements
continue; //bypass the followed instructions
break; //exit from the loop
return; //control returns to the caller
//it’s like goto
label:
- - - -
- - - -
break label;
statement
Type Conversion and Casting
⚫Type conversion, typecasting, refers to different ways
of, implicitly or explicitly, changing an entity of one data
type into another.
⚫Types of Conversions:
1.Widening conversion
2.Narrowing
conversion
Widening Conversion
The widening conversion is permitted in the following
cases:
⚫ byte to short, int, long, float, or double
⚫ short to int, long, float, or double
⚫ char to int, long, float, or double
⚫ int to long, float, or double
⚫ long to float or double
⚫ float to double
⚫ 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.
⚫ When these two conditions are met, a widening conversion
takes place.
Ex: char and boolean are not compatible with each other.
class Widening{
public static void main(String args[]){
short s;
int i1,i2;
byte
b1=10,b
2=20;
s=b1;
i1=b2;
//byte to short
//byte to int
System.out.println("byte to short conversion");
System.out.println(b1+ " " + s);
System.out.println("byte to int conversion");
System.out.println(b2+" "+i1);
char c='a';
i2=c; //char to int
System.out.println("char to int conversion");
System.out.println(c+" "+i2);
}
}
⚫ In general, the narrowing primitive conversion can occur
in these cases:
short to byte or char
char to byte or
short
int to byte, short, or char
long to byte, short, or char
float to byte, short, char,
int, or long
double to byte, short, char,
int, long, or float
⚫ Narrowing conversion is used to cast
Narrowing Conversion
public class Narrowing{
public static void main(String args[]){
byte b=2;
int
i=257;
double
d=323.14
2;
System.out.println("int to byte conversion");
b= (byte)i; //int to byte
System.out.println("i and b values: "+i+" "+b);
System.out.println("double to int conversion");
i=(int)d; //double to int
System.out.println("d amd i values: "+d+" "+i);
System.out.println("double to byte conversion");
b=(byte)d; //double to byte
System.out.println("d amd b values: "+d+" "+b);
Arrays
⚫An array is a group of like-typed variables that are
referred to by a common name.
⚫The operator new is used for dynamic
memory allocation.
⚫One-Dimensional Arrays:
type varname[];
varname = new type[size];
type varname[]=new type[size];
Ex:
Ex:
Ex:
int month[];
month = new int[12];
int varname[]=new int[size];
Multidimensional Arrays
⚫If month is a reference to an array, month.length will give
you the length of the array.
Initialization:
⚫int x[] = {1, 2, 3, 4};
⚫char []c = {‘a’, ‘b’, ‘c’};
⚫double d[][]= {
{1.0,2.0,3.0},
{4.0,5.0,6.0},
{7.0,8.0,9.0}
};
Jagged Array:
⚫int [][] x = new int[3][];
import java.util.Scanner;
class ArrayEx{
public static void main(String args[])
{ Scanner input=new
Scanner(System.in); int
a[]={10,20,30,40,50};
char []c={'a','b','c','d','e'};
int b[]=new int[5]; for(int
i=0;i<5;i++){
System.out.print(
a[i]+" ");
System.out.printl
n(c[i]+" ");
}
for(int i=0;i<5;i++){
b[i]=input.nextInt
();
}
for(int i=0;i<5;i++){
Concepts of Classes, Objects
General Form of Class
class classname {
type instance-variable1;
//...
type instance-variableN;
static type variable1;
type methodname1(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list){
// body of method
}
}
Declaring an Object
class Box{
double width;
double
height;
double depth;
}
Representation 1:
Box mybox;
mybox=new
Box();
Representation 2:
Box mybox=new
Box();
Representation 3: Assigning Object Reference
package
packagename;
import statement;
class classname{
//instance variables;
//class or static
variables;
/*methods(parameters){
//local variables;
//object
creation
//statements;
}*/
}
import java.util.Scanner;
class Demon{
int i;
static double d;
public static void main(String args[]){
char c=‘a’;
Demon obj=new Demon();
Scanner s=new Scanner(System.in);
d=s.nextDouble();
System.out.println(
obj.i);
System.out.println(d);
System.out.println(
c);
}
class classname{
//instance variables;
//class or static variables;
/*methods(parameters){
//local variables;
//statements;
}*/
}
class MainCLass{
public static void main(String args[])
{
//object creation
//invoking methods
//statements
}
}
class
Test{ char
c='a'; static
float f;
void display(){
int i=10;
System.out.println("Test:display()");
System.out.println(“c value: “+c);
System.out.println(“i value: “+i);
System.out.println(“f value: “+f);
}
}
class Demo{
public static void main(String args[])
{ Test t=new Test();
t.display();
System.out.println("Demo:main()");
}
}
Constructors and Methods
⚫ A constructor is a special member function whose task is to initialize an
object immediately upon creation.
⚫ The constructor is automatically called immediately after the object is
created.
⚫ A constructor has the same name as the class in which it resides and is
syntactically similar to a method.
⚫ If no constructor in program .System provides its own constructor
called as
default constructor.
⚫ Constructors doesn’t have any return type.
⚫ A constructor which accepts parameters is called as parameterized
constructor.
Default Constructor:
⚫ A constructor that accepts no parameters is called Default constructor.
⚫ If not defined, provided by the compiler.
⚫ The default constructor is called whenever an object is created
without specifying initial values.
Ex: class Box {
double width;
double height;
double depth;
Box() {
width
= 10;
heigh
t =
10;
depth
= 10;
}
}
// declare, allocate,
class Test{
int x,y;
Test(int a, int b){
x=a;
y=b;
System.out.println(“x value: “+x);
System.out.println(“y value: “+y);
}
}
class PConDemo{
public static void main(String args[]){
Test t=new Test(10,20);
System.out.println(“PConDemo:main()");
}
}
//Parameterized Constructor
// Non parameterized Default Constructor
class
Test{ char
c='a'; static
float f;
Test(){
int i=10;
System.out.println("Test:Test()");
System.out.println(“c value: “+c);
System.out.println(“i value: “+i);
System.out.println(“f value: “+f);
}
}
class ConDemo{
public static void main(String args[])
{ Test t=new Test();
//t.Test();
System.out.println(“ConDemo:main()");
}
}
Methods
General Form:
type name(parameter-list) {
// body of method
}
⚫The type of data returned by a method must be compatible
with the return type specified by the method.
⚫ The variable receiving the value returned by a method must
also be compatible with the return type specified for the
method.
return value; //Here, value is the value
returned.
Ex:
double volume(double w, double h, double d)
{ return w*h*d;
class
Box{ double
width;
double height;
double depth;
Box(){
width=10;
height=10;
depth=10;
}
double volume(){
return
width*height*d
epth;
}
class BoxDemo6{
public static void main(String args[]){
Box mybox1=new Box();
Box mybox2=new Box();
double vol;
vol=mybox1.volume();
System.out.println("Volume is: "+vol);
vol=mybox2.volume();
System.out.println("Volume is: "+vol);
}
}
Non parameterized or default
Constructor
class
Box{ double
width; double
height;
double depth;
Box(double w,double h,double d){
width=w;
height=h;
depth=d;
}
double volume(){
return width*height*depth;
}
}
class BoxDemo7{
public static void main(String args[]){
Box mybox1=new
Box(10,20,15); Box
mybox2=new Box(3,6,9);
double vol;
vol=mybox1.volume();
System.out.println("Volume is: "+vol);
vol=mybox2.volume();
System.out.println("Volume is: "+vol);
}
}
Parameterized
Constructor
default :
 When no access specifier is used, then by default the
member of a class is public within its own package, but
cannot be accessed outside of its package.
private:
 A private member is accessible only to the class in which it
is defined.
 Use private keyword to create private members.
Access Control
public:
 Anyclass,in any package has access to a class's
public members.
 To declare a public member, use the keyword public.
protected:
 Allows the class itself, subclasses, and all classes in the same
package to access the members.
 To declare a protected member, use the keyword protected.
class Test {
int a;
public int
b;
// default access
// public access
private int c; // private
access
/*protected applies only
when inheritance is involved*/
// methods to access c
void setc(int i){
c = i; // set c's
value
// get c's value
}
int getc() {
return c;
}
}
class AccessTest
{
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an
error
//ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println(ob.a + " " +ob.b + " " +
ob.getc());
}
}
//Example for access control
Method & Constructor Overloading
 Defining two or more methods within the same class that share the
same name is called method overloading.
 Java uses the type and/or number of arguments to determine
which version of the overloaded method to call.
 Constructors can also be overloaded in the same way as method
overloading.
class OverloadDemo
{ void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[])
{ OverloadDemo ob = new
OverloadDemo(); double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " +
result);
//method overloading
//Constructor
Overloading
class CDemo{
int value1;
int value2;
CDemo(){
value1
=
10;
value2
=
20;
System.out.pr
intln("Insid
e 1st
C
o
n
s
t
r
u
c
t
System.out.println("Inside 2nd Constructor");
}
CDemo(int a,int b){
value1 = a;
value2 =
b;
System.out
.println("In
side 3rd
Constructo
r");
public static void main(String args[]){
CDemo d1 = new CDemo();
CDemo d2 = new CDemo(30);
CDemo d3 = new CDemo(30,40);
d1.display();
d2.display();
d3.display();
}
}
this
⚫ In java, it is illegal to declare two local variables with the same name
inside the same or enclosing scopes.
⚫ But you can have formal parameters to methods, which overlap with the
names of the class’ instance variables.
⚫ this keyword is used to refer to the current object.
⚫ this can be used to resolve any name collisions that might occur
between instance variables and formal variables.
⚫ When a formal variable has the same name as an instance variable, the
formal variable hides the instance variable.
⚫ Also used in method chaining and constructor chaining.
// instance and formal variables are different
class Box{
double w=5,h=5,d=5;
Box(double w1,double h1,double d1){
w=w1;
h=h1;
d=d1;
}
double volume(){
return w*h*d;
}
}
class BoxTest1{
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is: "+b.volume());
}
}
Output:
Volume is:6.0
// instance and formal variables are same
class Box{
double w=5,h=5,d=5;
Box(double w,double h,double d){
w=w;
h=h;
d=d;
}
double volume(){
return w*h*d;
}
}
class BoxTest2{
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is: "+b.volume());
}
}
Output:
Volume is:125.0
//’this’ hides the instance
variables
class Box{
double w=5,h=5,d=5;
Box(double w,double h,double d){
this.w=w;
this.h=h;
this.d=d;
}
double volume(){
return w*h*d;
}
}
class BoxTest2{
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is: "+b.volume());
}
}
Output:
Volume is:6.0
class Fchain{ // method chaining
int a,b;
Fchain setValue(int x,int y){
a=x;
b=y; return this;
}
Fchain disp(){
System.out.println("a value is:"+a);
System.out.println("b value is:"+b);
return this;
}
}
class FchainDemo{
public static void main(String args[]){
Fchain f1=new Fchain();
f1.setValue(10,20).disp().setValue(11,22).disp();
}
}
//Constructor Chaining
class Test{
int a,b,c,d;
Test(int x,int y){
a=x;
b=y;
}
Test(int x,int
y,int z){
this(x,y);
c=z;
}
Test(int p,int
q,int r,int s){
this(p,q,r);
d=s;
}
void disp(){
System.out.println(a+” ”+b+” ”+c+” ”+d);
}
}
class TestDemo{
public static void main(String args[]){
Test t1=new Test(10,20,30,40);
t1.disp();
}
}
Parameter Passing
 The call-by-value copies the value of a actual parameter into
the formal parameter of the method.
 In this method, changes made to the formal parameter of the
method have no effect on the actual parameter.
 In call-by-reference, a reference to an actual parameter (not the
value of the argument) is passed to the formal parameter.
 In this method, changes made to the actual parameter will affect
the actual parameter used to call the method.
// Simple types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[])
{ Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +a + " " + b);
}
}
// Objects are passed by
reference. class Test {
// pass an object
int a, b;
Test(int i, int j) {
a = i;
b =
j;
}
void
meth(Test
o) {
a. *
=
2
;
b. /
=
2
;
}
}
}
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
}
class Box{ //call by reference
double width,height,depth;
Box(Box ob) {
width = ob.width;
height = ob.height;
depth = ob.depth;
}
Box(double w, double h,
double d){
width = w;
height =
h; depth =
d;
}
Box(){
width = -
1;
height = -
1;
depth = -
1;
}
Box(double len)
{
class OverloadCons2 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}
Garbage Collection
⚫ Garbage collection done automatically in java.
⚫ When no reference to an object exist, that object is assumed to
be no loner needed, and the memory occupied by the object can
be reclaimed.
⚫ Garbage collection only occurs at regular intervals during the
execution of your program.
⚫ We can run garbage collection on demand by calling the gc()
method.
⚫ public static void gc(): Initiates the garbage collection.
System.gc();
public class GarbageCollector{
public static void main(String[] args) {
int SIZE = 200;
StringBuffer s;
for (int i = 0; i < SIZE; i++) {
}
System.out.println("Garbage Collection started explicitly.");
System.gc();
}
}
finalize( )
method
⚫ Sometimes an object will need to perform some action when it
is destroyed.
Ex:
If an object is holding some non-java resource such as a file, then you
might want to make sure these resources are freed before an object is
destroyed.
⚫ Tohandle such situations, Java provides a mechanism
called
finalization.
⚫ The finalize( ) method has this general form:
protected void finalize( ){
// finalization code here
}

More Related Content

PPTX
object oriented programming unit one ppt
PPTX
UNIT 1.pptx
PPTX
Unit1 introduction to Java
PPT
Object Oriented Programming-JAVA
PPT
introduction_to_core_elementry_java-1.ppt
PDF
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
object oriented programming unit one ppt
UNIT 1.pptx
Unit1 introduction to Java
Object Oriented Programming-JAVA
introduction_to_core_elementry_java-1.ppt
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf

Similar to Java Technologies notes of unit 1 and 2. (20)

PPTX
UNIT 1 Programming in java Bsc program.pptx
PPT
Introduction to Java Programming, Basic Structure, variables Data type, input...
PDF
Unit 1 Core Java for Compter Science 3rd
PPTX
Java. converted (2)
PPTX
Java Programming
PDF
Java programming material for beginners by Nithin, VVCE, Mysuru
PPTX
java slides
PDF
Object Oriented Programming slides that can help students
PPTX
Java Basics in Mule
PPTX
Java Basics
PPTX
Java in Mule
PPTX
Introduction to java
PPTX
Introduction to java
PPTX
Java
PPTX
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
PDF
Core java part1
PPT
javaeanjjisjejrehurfhjhjfeauojksfjdi.ppt
PPTX
Introduction to java
PPTX
Java Introduction
PPTX
UNIT 1 Programming in java Bsc program.pptx
Introduction to Java Programming, Basic Structure, variables Data type, input...
Unit 1 Core Java for Compter Science 3rd
Java. converted (2)
Java Programming
Java programming material for beginners by Nithin, VVCE, Mysuru
java slides
Object Oriented Programming slides that can help students
Java Basics in Mule
Java Basics
Java in Mule
Introduction to java
Introduction to java
Java
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
Core java part1
javaeanjjisjejrehurfhjhjfeauojksfjdi.ppt
Introduction to java
Java Introduction
Ad

Recently uploaded (20)

PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
Construction Project Organization Group 2.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
web development for engineering and engineering
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
Digital Logic Computer Design lecture notes
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
PPT on Performance Review to get promotions
PPTX
Artificial Intelligence
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPT
Project quality management in manufacturing
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
CH1 Production IntroductoryConcepts.pptx
Construction Project Organization Group 2.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
web development for engineering and engineering
Lecture Notes Electrical Wiring System Components
Internet of Things (IOT) - A guide to understanding
Digital Logic Computer Design lecture notes
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
OOP with Java - Java Introduction (Basics)
Foundation to blockchain - A guide to Blockchain Tech
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPT on Performance Review to get promotions
Artificial Intelligence
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Project quality management in manufacturing
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Ad

Java Technologies notes of unit 1 and 2.

  • 2. SYLLABUS Unit - I Concept of OOPS, History of Java, how Java works, Java Virtual Machine(JVM), Java In Time(JIT) compiler, Java features, Java application types. Data types, Operators, If Statements, Switch Statement, Loops, Arrays, casting, command line arguments. UNIT II Java Classes and Memory Management Introduction to Classes, objects, Constructors, inheritance (Single, Multilevel, Hybrid), Abstraction, encapsulation, polymorphism, finalizes, garbage collection, access specifier, Java interface, Packages.
  • 3. History of Java ⚫ Java started out as a research project. ⚫ Research began in 1991 as the Green Project at Sun Microsystems, Inc. ⚫ Research efforts birthed a new language, OAK. ( A tree outside of the window of James Gosling’s office at Sun). ⚫It was developed as an embedded programming language, which would enable embedded system application. ⚫It was not really created as web programming language. ⚫Java is available as jdk and it is an open source s/w.
  • 4. History of Java (contd…) Language was created with 5 main goals:  It should be object oriented.  A single representation of a program could be executed on multiple operating systems. (i.e. write once, run anywhere)  It should fully support network programming.  It should execute code from remote sources securely.  It should be easy to use. ⚫ Oak was renamed Java in 1994. ⚫Now Sun Microsystems is a subsidiary of Oracle Corporation.
  • 8. Versions of Java Version Codename Year Features Added JDK 1.0 Oak Jan23,1996 - JDK 1.1 Rebirth of Java Feb19,1997 Inner classes JavaBeans, JDBC, RMI, Reflection, AWT. J2SE 1.2 Playground Dec8, 1998 JIT compiler, Collections, IDL & CORBA, strictfp, Java Plug-in. J2SE 1.3 Kestrel May8, 2000 HotSpot JVM, JavaSound, Java Naming and Directory Interface, Java Platform Debugger Architecture. J2SE 1.4 Merlin Feb6, 2002 Preferences API, Logging API, assert, image I/O API, security and cryptography extensions. J2SE 5.0 Tiger Sep30, 2004 Generics, annotations, Autoboxing, Enumerations, Varargs, Enhanced for each. JA VA SE 6 Mustang Dec11, 2006 JDBC 4.0, JVM improvements, Improved JAXB, Improved web services, Support for older Win9x versions dropped. JA VA SE 7 Dolphin July28, 2011 Major updates to Java JA VA SE 8 - 2012 -
  • 9. Java Platforms There are three main platforms for Java: ⚫Java SE (Java Platform, Standard Edition) – runs on desktops and laptops. ⚫Java ME (Java Platform, Micro Edition) – runs on mobile devices such as cell phones. ⚫Java EE (Java Platform, Enterprise Edition) – runs on servers.
  • 10. Java Development Kit: It contains one (or more) JRE's along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc. Java Virtual Machine: An abstract machine architecture specified by the Java Virtual Machine Specification. It interprets the byte code into the machine code depending upon the underlying OS and hardware combination. JVM is platform dependent. (It uses the class libraries, and other supporting files provided in JRE) Java Terminology
  • 11. Java Runtime Environment: A runtime environment which implements Java Virtual Machine, and provides all class libraries and other facilities necessary to execute Java programs. This is the software on your computer that actually runs Java programs. JRE = JVM + Java Packages Classes (like util, math, lang, awt, swing etc) +runtime libraries. Java Terminology (contd…)
  • 12. Java Source Java Byte codes Java Byte codes move locally or through n/w Java Compiler Class Loader Byte Code Verifier Java Class Libraries Java Interpreter Just-in-time Compiler Run Time System Java OS Win 32 Solaris MAC Others Hardware Java Execution Procedure
  • 13. The Architecture of the Java Virtual Machine
  • 14. Java Virtual Machine ⚫Class loader subsystem: A mechanism for loading types (classes and interfaces) given fully qualified names. ⚫The Java virtual machine organizes the memory it needs to execute a program into several runtime data areas. ⚫Each Java virtual machine also has an execution engine: a mechanism responsible for executing the instructions contained in the methods of loaded classes.
  • 15. Object Oriented Programming Concepts ⚫Objects ⚫Classes ⚫Data abstraction and Encapsulation ⚫Inheritance ⚫Polymorphism ⚫Dynamic Binding
  • 16. A class is collection of objects of similar type or it is a template. Ex: fruit mango; class object Objects are instances of the type class. The wrapping up of data and functions into a single unit ( called class) is known as encapsulation. Data encapsulation is the most striking features of a class. Abstraction refers to the act of representing essential features without including the background details or explanations Inheritance is the process by which objects of one class acquire the properties of another class. The concept of inheritance provides the reusability.
  • 17. Polymorphism: It allows the single method to perform different actions based on the parameters. Dynamic Binding: When a method is called within a program, it associated with the program at run time rather than at compile time is called dynamic binding.
  • 20. C++ JA V A C++ supports pointers Java does not pointers C++ run and compile using compiler which converts source code into machine level languages so c++ is plate from dependents At compilation time Java Source code converts into byte code .The interpreter execute this byte code at run time and gives output .Java is interpreted for the most part and hence platform independent c++ is depends upon operating system machine etc Java is platform independent language c++ their is only compiler Java uses compiler and interpreter both C++ supports operator overloading java does not. Thread support is not available in Java Thread support is built-in Java Internet support does not exist Internet support is built-in Java but not in C++. Java does not support header file, include library files just like C++ . Java use import to include different Classes and methods. Goto statement exist in C++ There is no goto statement in Java. operator overloading exist in c++. Java has method overloading, but no operator overloading just like c++. C++ support unsigned integer. Java does not support unsigned integer.
  • 21. Features of Java  Simple  Object Oriented  Compile, Interpreted and High Performance  Portable  Reliable  Secure  Multithreaded  Dynamic  Distributed  Architecture-Neutral
  • 22. Java Features ⚫ Simple ⚫No pointers ⚫Automatic garbage collection ⚫Rich pre-defined class library ⚫ Object Oriented ⚫Focus on the data (objects) and methods manipulating the data ⚫All methods are associated with objects ⚫Potentially better code organization and reuse
  • 23. ⚫Compile, Interpreted and High Performance ⚫Java compiler generate byte-codes, not native machine code ⚫The compiled byte-codes are platform-independent ⚫Java byte codes are translated on the fly to machine readable instructions in runtime (Java Virtual Machine) ⚫Easy to translate directly into native machine code by using a just-in-time compiler. ⚫Portable ⚫Same application runs on all platforms ⚫The sizes of the primitive data types are always the same ⚫The libraries define portable interfaces Java Features
  • 24. Java Features ⚫Reliable/Robust ⚫Extensive compile-time and runtime error checking ⚫No pointers but real arrays. Memory corruptions or unauthorized memory accesses are impossible ⚫Automatic garbage collection tracks objects usage over time ⚫Secure ⚫Java’s robustness features makes java secure. ⚫Access restrictions are forced (private, public)
  • 25. Java Features ⚫Multithreaded ⚫It supports multithreaded programming. ⚫Need not wait for the application to finish one task before beginning another one. ⚫Dynamic ⚫Libraries can freely add new methods and instance variables without any effect on their clients ⚫Interfaces promote flexibility and reusability in code by specifying a set of methods an object can perform, but leaves open how these methods should be implemented .
  • 26. Java Features ⚫Distributed ⚫Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. ⚫ Allows objects on two different computers to execute procedures remotely by using package called Remote Method Invocation (RMI). ⚫Architecture-Neutral ⚫Goal of java designers is “write once; run anywhere, any time, forever.”
  • 27. Data Types Simple Type User Defined Type Numeric Type Non- Numeric clas s Interface Intege r Floa t Char Boolean floa t doubl e byt e shor t int long Derived Type E.g: Array, String…
  • 28. Data Types ⚫Java Is a Strongly Typed Language ⚫ Every variable has a type, every expression has a type, and every type is strictly defined. ⚫ All assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. ⚫ There are no automatic conversions of conflicting types as in some languages. ⚫ For example, in C/C++ you can assign a floating-point value to an integer. In Java, you cannot.
  • 29. Integer Data Types  Java does not support unsigned, positive-only integers.  All are signed, positive and negative values. Byte Data Type  The smallest integer type is byte.  Variables of type byte are especially useful while working with a stream of data from a network or file.  Byte variables are declared by use of the byte keyword. Ex: byte b, c; Floating Point Types  There are two kinds of floating-point types.  All math functions, such as sin( ), cos( ), and sqrt( ), return double values. Boolean DataType  It can have only one of two possible values, true or false.
  • 30. Character Data Type  char in Java is not the same as char in C or C++.  Java uses Unicode to represent characters.  Unicode defines a fully international character set that can represent all of the characters found in all human languages.  It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more.  Hence it requires 16 bits.  The range of a char in java is 0 to 65,536.  There are no negative chars.
  • 31. Data Types Width in bits Range Name long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 int 32 –2,147,483,648 to 2,147,483,647 short 16 –32,768 to 32,767 byte 8 –128 to 127 double 64 4.9e–324 to 1.8e+308 float 32 1.4e−045 to 3.4e+038 char 16 0 to 65,536.
  • 32. public class IntDemo{ public static void main(String args[]){ System.out.println(" For an Integer "); System.out.println("Size is : "+Integer.SIZE); int i1 = Integer.MAX_VALUE; int i2 = Integer.MIN_VALUE ; System.out.println("Max value is : "+i1); System.out.println("Min Value is : "+i2); System.out.println(" For an Byte"); System.out.println("Size is : "+Byte.SIZE); byte b1 = Byte.MAX_VALUE; byte b2 = Byte.MIN_VALUE ; System.out.println("Max value is : "+b1); System.out.println("Min Value is : "+b2); System.out.println(" For an Short"); System.out.println("Size is : "+Short.SIZE); short s1 = Short.MAX_VALUE; short s2 = Short.MIN_VALUE ; System.out.println("Max value is : "+s1); System.out.println("Min Value is : "+s2); System.out.println(" For an Long"); System.out.println("Size is : "+Long.SIZE); long l1 = Long.MAX_VALUE; long l2 = Long.MIN_VALUE ; System.out.println("Max value is : "+l1); System.out.println("Min Value is : "+l2); } }
  • 33. public class FloatDemo{ public static void main(String args[]){ System.out.println(" For an Float"); System.out.println("Size is : "+Float.SIZE); float f1 = Float.MAX_VALUE; float f2 = Float.MIN_VALUE ; System.out.println("Max value is : "+f1); System.out.println("Min Value is : "+f2); System.out.println(" For an Double"); System.out.println("Size is : "+Double.SIZE); double d1 = Double.MAX_VALUE; double d2 = Double.MIN_VALUE ; System.out.println("Max value is : "+d1); System.out.println("Min Value is : "+d2); } }
  • 34. public class CharDemo{ public static void main(String args[]){ System.out.println(" For a Char"); System.out.println("Size is : "+Character.SIZE); int f1 = Character.MAX_VALUE; long f2 = Character.MIN_VALUE ; System.out.println("Max value is : "+f1); System.out.println("Min Value is : "+f2); }
  • 35. Variables  The variable is the basic unit of storage in a Java program.  A variable is defined by the combination of an identifier, a type, and an optional initializer. Declaring a Variable  In Java, all variables must be declared before they can be used. type identifier [ = value][, identifier [= value] ...] ; Types  Instance Variable  Class Variable  Local Variable  Parameters
  • 36. Local variables : • Local variables are declared in methods, constructors, or blocks. • Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block. • Access modifiers cannot be used for local variables. • Local variables are visible only within the declared method, constructor or block. • There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.
  • 37. Instance variables : • Instance variables are declared in a class, but outside a method, constructor or any block. • Instance variables are created when an object is created with the use of the key word 'new' and destroyed when the object is destroyed. • Access modifiers can be given for instance variables. • The instance variables are visible for all methods, constructors and block in the class. • Instance variables have default values. • Instance variables can be accessed directly by calling the variable name inside the class. • However within static methods and different class ( when instance variables are given accessibility) that should be called using the fully qualified name ObjectReference.VariableName
  • 38. Class/Static variables : • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. • There would only be one copy of each class variable per class, regardless of how many objects are created from it. • Static variables are stored in static memory. • Static variables are created when the program starts and destroyed when the program stops. • Visibility is similar to instance variables. • Default values are same as instance variables. • Static variables can be accessed by calling with the class name ClassName.VariableName
  • 39. class Variables{ i nt i; public int j static long l=10; public static float f; char c; boolean b; void display(int a){ i=a; System.out.println( "i value in display: "+i); } public static void main(String args[]) { double d=0.0; //public double d=0.0; invalid Variables v1=new Variables(); Variables v2=new Variables(); System.out.println("i value is: "+v1.i); System.out.println("i value is: "+v2.i); System.out.println("i value is: "+v3.i); System.out.println("i value is: "+v1.j); v1.l=20; v2.l=30; v3.l=40; System.out.println("l value is: "+v1.l); System.out.println("l value is: "+v2.l); System.out.println("l value is: "+v3.l); System.out.println("f value is: "+f); System.out.println("c value is: "+v1.c); System.out.println("b value is: "+v1.b); System.out.println("d value is: "+d); } }
  • 40. class Variables{ int i;//instance variable public int j ;//instance variable static long l=10;//class variable public static float f;//class variable char c;//instance variable boolean b;//instance variable void display(int a){ i=a; System.out.println("i value in display: "+i); } public static void main(String args[]){ double d=0.0;//local varible //public double d=0.0; invalid Variables v1=new Variables(); Variables v2=new Variables(); Variables v3=new Variables(); v1.display(100); System.out.println("i value is: "+v1.i); System.out.println("i value is: "+v2.i); System.out.println("i value is: "+v3.i); System.out.println("i value is: "+v1.j); v1.l=20; v2.l=30; v3.l=40; System.out.println("l value is: "+v1.l); System.out.println("l value is: "+v2.l); System.out.println("l value is: "+v3.l); System.out.println("f value is: "+f); System.out.println("c value is: "+v1.c); System.out.println("b value is: "+v1.b); System.out.println("d value is: "+d); } }
  • 41. Sample Program class HelloWorld { public static void main (String args []) { System.out.println (“Welcome to Java Programming…..”); } } public allows the program to control the visibility of class members.When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. In this case, main ( ) must be declared as public, since it must be called by code outside of its class when the program is started.
  • 42. static allows main( ) to be called without having to instantiate a particular instance of the class.This is necessary since main ( ) is called by the Java interpreter before any objects are made. void states that the main method will not return any value. main() is called when a Java application begins. In order to run a class, the class must have a main method. string args[] declares a parameter named args, which is an array of String. In this case, args receives any command-line arguments present when the program is executed.
  • 43. System is a class which is present in java.lang package. out is a static field present in system class which returns a PrintStream object. As out is a static field it can call directly with classname. println() is a method which present in PrintStream class which can call through the PrintStream object return by static field out present in System class to print a line to console.
  • 44. class sample{ public static void main(String args[]){ System.out.println("sample:main" ); sample s=new sample(); s.display(); } void display(){ System.out.println("display:main"); } }
  • 45. The Scope and Lifetime of Variables Scope The scope of a declared element is the portion of the program where the element is visible. Lifetime The lifetime of a declared element is the period of time during which it is alive. The lifetime of the variable can be determined by looking at the context in which they're defined.  Java allows variables to be declared within any block.  A block begins with an opening curly brace and ends by a closing curly brace.
  • 46. ⚫ Variables declared inside a scope are not accessible to code outside. ⚫ Scopes can be nested. The outer scope encloses the inner scope. ⚫ Variables declared in the outer scope are visible to the inner scope. ⚫ Variables declared in the inner scope are not visible to the outside scope.
  • 47. public class Scope { public static void main(String args[]){ int x; //know to all code within main x=10; if(x==10){ // starts new scope int y=20; //Known only to this block //x and y both known here System.out.println("x and y: "+x+" "+y); x=y+2; } // y=100; // error ! y not known here //x is still known here System.out.println("x is "+x); } }
  • 49. Arithmetic Operators(1) Operator Result + Addition – Subtraction * Multiplication / Division % Modulus
  • 50. Arithmetic Operators(2) Operator Result ++ Increment += Addition assignment – = Subtraction assignment *= Multiplication assignment / = Division assignment %= Modulus assignment – – Decrement
  • 51. Example : class IncDec{ public static void main(String args[]){ int a = 1; int b = 2; int c,d; c = ++b; d = a+ +; c++; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); } }
  • 52. class OpEquals{ public static void main(String args[]){ int a = 1; int b = 2; int c = 3; a += 5; b *= 4; c += a * b; c %= 6; System.out. println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c);
  • 53. Bitwise Operators(1)  bitwise operators can be applied to the integer types, long, int, short, byte and char.  These operators act upon the individual bits of their operands. Operato r ~ & | ^ >> >>> << Result Bitwise unary NOT Bitwise AND Bitwise OR Bitwise exclusive OR Shift right Shift right zero fill Shift left
  • 54. Bitwise Operators(2) Operator Result &= Bitwise AND assignment | = Bitwise OR assignment ^= Bitwise exclusive OR assignment >>= Shift right assignment >>>= Shift right zero fill assignment <<= Shift left assignment
  • 55. 0010101 0 &0000111 1 42 15 0000101 0 10 0010101 0 ^00001111 42 15 0010010 1 37 int a = 32; a = a >> 2; 8 int a = 64; a = a << 2; 256 –8 1111100 0 >>1 1111110 0 –4 –1 11111111 11111111 11111111 11111111 >>>24 00000000 00000000 00000000 11111111 255
  • 56. Relational Operators  The relational operators determine the relationship that one operand has to the other.  They determine equality and ordering. Operato r == != > < >= <= Result Equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to
  • 57. Example : public class RelationalOperatorsDemo { public static void main(String args[]) { int x=10,y=5; System.out.println(“x>y:”+ (x>y)); System.out.println(“x<y:”+(x<y)); System.out.println(“x>=y:”+ (x>=y)); System.out.println(“x<=y:”+ (x<=y)); System.out.println(“x==y:”+ (x==y)); System.out.println(“x! =y:”+(x!=y)); } }
  • 58. Boolean Logical Operators(1)  The Boolean logical operators operate only on boolean operands.  All of the binary logical operators combine two boolean values to form a resultant boolean value. Operator Result & | ^ | | & & ! Logical AND Logical OR Logical XOR (exclusive OR) Short-circuit OR Short-circuit AND Logical unary NOT
  • 59. & //executes both left and right side operands && // Java will not bother to evaluate the right- hand operand when the outcome of the expression can be determined by the left operand alone. class Test{ public static void main(String args[]){ int denom=0,num=20; if (denom != 0 && num / denom > 10) System.out.println("Hi"); } }
  • 60. Boolean Logical Operators(2) Operator Result &= AND assignment | = OR assignment ^= XOR assignment == Equal to != Not equal to ?: Ternary if-then- else
  • 62. public class TernaryOperatorDemo { public static void main(String args[]) { int x=10,y=12; int z; z= x > y ? x : y; System.out.pri ntln(“Z=“+z); }
  • 64. Expressions ⚫An expression is a combination of constants (like 10), operators ( like +), variables(section of memory) and parentheses ( like “(” and “)” ) used to calculate a value. Ex1 : Ex2 : Ex3 : x = 1; y = 100 + x; x = (32 - y) / (x + 5)
  • 65. Control Statements if & switch ⚫Selection Statements: ⚫Iteration Statements: ⚫Jump Statements: for, while and do-while break, continue and return
  • 66. Selection Statements if (condition) statement1; else statement2; if(condition) statement; else if(condition) statement; else if(condition) statement; ... else statement; switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break; … case valueN: // statement sequence break; default: // default statement sequence }
  • 67. The condition is any expression that returns a boolean value. The expression must be of type byte, short, int, or char; Each of the values specified in the case statements must be of a type compatible with the expression.
  • 68. Iteration Statements while(condition) { / / body of loop } d o {/ / body of loop } while (condition); for(initialization; condition; iteration) { / / body }
  • 69. Jump Statements continue; //bypass the followed instructions break; //exit from the loop return; //control returns to the caller //it’s like goto label: - - - - - - - - break label; statement
  • 70. Type Conversion and Casting ⚫Type conversion, typecasting, refers to different ways of, implicitly or explicitly, changing an entity of one data type into another. ⚫Types of Conversions: 1.Widening conversion 2.Narrowing conversion
  • 71. Widening Conversion The widening conversion is permitted in the following cases: ⚫ byte to short, int, long, float, or double ⚫ short to int, long, float, or double ⚫ char to int, long, float, or double ⚫ int to long, float, or double ⚫ long to float or double ⚫ float to double
  • 72. ⚫ 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. ⚫ When these two conditions are met, a widening conversion takes place. Ex: char and boolean are not compatible with each other.
  • 73. class Widening{ public static void main(String args[]){ short s; int i1,i2; byte b1=10,b 2=20; s=b1; i1=b2; //byte to short //byte to int System.out.println("byte to short conversion"); System.out.println(b1+ " " + s); System.out.println("byte to int conversion"); System.out.println(b2+" "+i1); char c='a'; i2=c; //char to int System.out.println("char to int conversion"); System.out.println(c+" "+i2); } }
  • 74. ⚫ In general, the narrowing primitive conversion can occur in these cases: short to byte or char char to byte or short int to byte, short, or char long to byte, short, or char float to byte, short, char, int, or long double to byte, short, char, int, long, or float ⚫ Narrowing conversion is used to cast Narrowing Conversion
  • 75. public class Narrowing{ public static void main(String args[]){ byte b=2; int i=257; double d=323.14 2; System.out.println("int to byte conversion"); b= (byte)i; //int to byte System.out.println("i and b values: "+i+" "+b); System.out.println("double to int conversion"); i=(int)d; //double to int System.out.println("d amd i values: "+d+" "+i); System.out.println("double to byte conversion"); b=(byte)d; //double to byte System.out.println("d amd b values: "+d+" "+b);
  • 76. Arrays ⚫An array is a group of like-typed variables that are referred to by a common name. ⚫The operator new is used for dynamic memory allocation. ⚫One-Dimensional Arrays: type varname[]; varname = new type[size]; type varname[]=new type[size]; Ex: Ex: Ex: int month[]; month = new int[12]; int varname[]=new int[size];
  • 78. ⚫If month is a reference to an array, month.length will give you the length of the array. Initialization: ⚫int x[] = {1, 2, 3, 4}; ⚫char []c = {‘a’, ‘b’, ‘c’}; ⚫double d[][]= { {1.0,2.0,3.0}, {4.0,5.0,6.0}, {7.0,8.0,9.0} }; Jagged Array: ⚫int [][] x = new int[3][];
  • 79. import java.util.Scanner; class ArrayEx{ public static void main(String args[]) { Scanner input=new Scanner(System.in); int a[]={10,20,30,40,50}; char []c={'a','b','c','d','e'}; int b[]=new int[5]; for(int i=0;i<5;i++){ System.out.print( a[i]+" "); System.out.printl n(c[i]+" "); } for(int i=0;i<5;i++){ b[i]=input.nextInt (); } for(int i=0;i<5;i++){
  • 81. General Form of Class class classname { type instance-variable1; //... type instance-variableN; static type variable1; type methodname1(parameter-list) { // body of method } // ... type methodnameN(parameter-list){ // body of method } }
  • 82. Declaring an Object class Box{ double width; double height; double depth; } Representation 1: Box mybox; mybox=new Box(); Representation 2: Box mybox=new Box(); Representation 3: Assigning Object Reference
  • 83. package packagename; import statement; class classname{ //instance variables; //class or static variables; /*methods(parameters){ //local variables; //object creation //statements; }*/ } import java.util.Scanner; class Demon{ int i; static double d; public static void main(String args[]){ char c=‘a’; Demon obj=new Demon(); Scanner s=new Scanner(System.in); d=s.nextDouble(); System.out.println( obj.i); System.out.println(d); System.out.println( c); }
  • 84. class classname{ //instance variables; //class or static variables; /*methods(parameters){ //local variables; //statements; }*/ } class MainCLass{ public static void main(String args[]) { //object creation //invoking methods //statements } } class Test{ char c='a'; static float f; void display(){ int i=10; System.out.println("Test:display()"); System.out.println(“c value: “+c); System.out.println(“i value: “+i); System.out.println(“f value: “+f); } } class Demo{ public static void main(String args[]) { Test t=new Test(); t.display(); System.out.println("Demo:main()"); } }
  • 86. ⚫ A constructor is a special member function whose task is to initialize an object immediately upon creation. ⚫ The constructor is automatically called immediately after the object is created. ⚫ A constructor has the same name as the class in which it resides and is syntactically similar to a method. ⚫ If no constructor in program .System provides its own constructor called as default constructor. ⚫ Constructors doesn’t have any return type. ⚫ A constructor which accepts parameters is called as parameterized constructor.
  • 87. Default Constructor: ⚫ A constructor that accepts no parameters is called Default constructor. ⚫ If not defined, provided by the compiler. ⚫ The default constructor is called whenever an object is created without specifying initial values. Ex: class Box { double width; double height; double depth; Box() { width = 10; heigh t = 10; depth = 10; } } // declare, allocate,
  • 88. class Test{ int x,y; Test(int a, int b){ x=a; y=b; System.out.println(“x value: “+x); System.out.println(“y value: “+y); } } class PConDemo{ public static void main(String args[]){ Test t=new Test(10,20); System.out.println(“PConDemo:main()"); } } //Parameterized Constructor // Non parameterized Default Constructor class Test{ char c='a'; static float f; Test(){ int i=10; System.out.println("Test:Test()"); System.out.println(“c value: “+c); System.out.println(“i value: “+i); System.out.println(“f value: “+f); } } class ConDemo{ public static void main(String args[]) { Test t=new Test(); //t.Test(); System.out.println(“ConDemo:main()"); } }
  • 89. Methods General Form: type name(parameter-list) { // body of method } ⚫The type of data returned by a method must be compatible with the return type specified by the method. ⚫ The variable receiving the value returned by a method must also be compatible with the return type specified for the method. return value; //Here, value is the value returned. Ex: double volume(double w, double h, double d) { return w*h*d;
  • 90. class Box{ double width; double height; double depth; Box(){ width=10; height=10; depth=10; } double volume(){ return width*height*d epth; } class BoxDemo6{ public static void main(String args[]){ Box mybox1=new Box(); Box mybox2=new Box(); double vol; vol=mybox1.volume(); System.out.println("Volume is: "+vol); vol=mybox2.volume(); System.out.println("Volume is: "+vol); } } Non parameterized or default Constructor
  • 91. class Box{ double width; double height; double depth; Box(double w,double h,double d){ width=w; height=h; depth=d; } double volume(){ return width*height*depth; } } class BoxDemo7{ public static void main(String args[]){ Box mybox1=new Box(10,20,15); Box mybox2=new Box(3,6,9); double vol; vol=mybox1.volume(); System.out.println("Volume is: "+vol); vol=mybox2.volume(); System.out.println("Volume is: "+vol); } } Parameterized Constructor
  • 92. default :  When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package. private:  A private member is accessible only to the class in which it is defined.  Use private keyword to create private members. Access Control
  • 93. public:  Anyclass,in any package has access to a class's public members.  To declare a public member, use the keyword public. protected:  Allows the class itself, subclasses, and all classes in the same package to access the members.  To declare a protected member, use the keyword protected.
  • 94. class Test { int a; public int b; // default access // public access private int c; // private access /*protected applies only when inheritance is involved*/ // methods to access c void setc(int i){ c = i; // set c's value // get c's value } int getc() { return c; } } class AccessTest { public static void main(String args[]) { Test ob = new Test(); // These are OK, a and b may be accessed directly ob.a = 10; ob.b = 20; // This is not OK and will cause an error //ob.c = 100; // Error! // You must access c through its methods ob.setc(100); // OK System.out.println(ob.a + " " +ob.b + " " + ob.getc()); } } //Example for access control
  • 95. Method & Constructor Overloading  Defining two or more methods within the same class that share the same name is called method overloading.  Java uses the type and/or number of arguments to determine which version of the overloaded method to call.  Constructors can also be overloaded in the same way as method overloading.
  • 96. class OverloadDemo { void test() { System.out.println("No parameters"); } void test(int a) { System.out.println("a: " + a); } void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); //method overloading
  • 97. //Constructor Overloading class CDemo{ int value1; int value2; CDemo(){ value1 = 10; value2 = 20; System.out.pr intln("Insid e 1st C o n s t r u c t System.out.println("Inside 2nd Constructor"); } CDemo(int a,int b){ value1 = a; value2 = b; System.out .println("In side 3rd Constructo r"); public static void main(String args[]){ CDemo d1 = new CDemo(); CDemo d2 = new CDemo(30); CDemo d3 = new CDemo(30,40); d1.display(); d2.display(); d3.display(); } }
  • 98. this ⚫ In java, it is illegal to declare two local variables with the same name inside the same or enclosing scopes. ⚫ But you can have formal parameters to methods, which overlap with the names of the class’ instance variables. ⚫ this keyword is used to refer to the current object. ⚫ this can be used to resolve any name collisions that might occur between instance variables and formal variables. ⚫ When a formal variable has the same name as an instance variable, the formal variable hides the instance variable. ⚫ Also used in method chaining and constructor chaining.
  • 99. // instance and formal variables are different class Box{ double w=5,h=5,d=5; Box(double w1,double h1,double d1){ w=w1; h=h1; d=d1; } double volume(){ return w*h*d; } } class BoxTest1{ public static void main(String args[]){ Box b=new Box(1,2,3); System.out.println("Volume is: "+b.volume()); } } Output: Volume is:6.0
  • 100. // instance and formal variables are same class Box{ double w=5,h=5,d=5; Box(double w,double h,double d){ w=w; h=h; d=d; } double volume(){ return w*h*d; } } class BoxTest2{ public static void main(String args[]){ Box b=new Box(1,2,3); System.out.println("Volume is: "+b.volume()); } } Output: Volume is:125.0
  • 101. //’this’ hides the instance variables class Box{ double w=5,h=5,d=5; Box(double w,double h,double d){ this.w=w; this.h=h; this.d=d; } double volume(){ return w*h*d; } } class BoxTest2{ public static void main(String args[]){ Box b=new Box(1,2,3); System.out.println("Volume is: "+b.volume()); } } Output: Volume is:6.0
  • 102. class Fchain{ // method chaining int a,b; Fchain setValue(int x,int y){ a=x; b=y; return this; } Fchain disp(){ System.out.println("a value is:"+a); System.out.println("b value is:"+b); return this; } } class FchainDemo{ public static void main(String args[]){ Fchain f1=new Fchain(); f1.setValue(10,20).disp().setValue(11,22).disp(); } }
  • 103. //Constructor Chaining class Test{ int a,b,c,d; Test(int x,int y){ a=x; b=y; } Test(int x,int y,int z){ this(x,y); c=z; } Test(int p,int q,int r,int s){ this(p,q,r); d=s; } void disp(){ System.out.println(a+” ”+b+” ”+c+” ”+d); } } class TestDemo{ public static void main(String args[]){ Test t1=new Test(10,20,30,40); t1.disp(); } }
  • 104. Parameter Passing  The call-by-value copies the value of a actual parameter into the formal parameter of the method.  In this method, changes made to the formal parameter of the method have no effect on the actual parameter.  In call-by-reference, a reference to an actual parameter (not the value of the argument) is passed to the formal parameter.  In this method, changes made to the actual parameter will affect the actual parameter used to call the method.
  • 105. // Simple types are passed by value. class Test { void meth(int i, int j) { i *= 2; j /= 2; } } class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " +a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " +a + " " + b); } }
  • 106. // Objects are passed by reference. class Test { // pass an object int a, b; Test(int i, int j) { a = i; b = j; } void meth(Test o) { a. * = 2 ; b. / = 2 ; } } } public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b); }
  • 107. class Box{ //call by reference double width,height,depth; Box(Box ob) { width = ob.width; height = ob.height; depth = ob.depth; } Box(double w, double h, double d){ width = w; height = h; depth = d; } Box(){ width = - 1; height = - 1; depth = - 1; } Box(double len) { class OverloadCons2 { public static void main(String args[]) { Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); Box myclone = new Box(mybox1); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); vol = mycube.volume(); System.out.println("Volume of cube is " + vol); vol = myclone.volume(); System.out.println("Volume of clone is " + vol); } }
  • 108. Garbage Collection ⚫ Garbage collection done automatically in java. ⚫ When no reference to an object exist, that object is assumed to be no loner needed, and the memory occupied by the object can be reclaimed. ⚫ Garbage collection only occurs at regular intervals during the execution of your program. ⚫ We can run garbage collection on demand by calling the gc() method. ⚫ public static void gc(): Initiates the garbage collection. System.gc();
  • 109. public class GarbageCollector{ public static void main(String[] args) { int SIZE = 200; StringBuffer s; for (int i = 0; i < SIZE; i++) { } System.out.println("Garbage Collection started explicitly."); System.gc(); } }
  • 110. finalize( ) method ⚫ Sometimes an object will need to perform some action when it is destroyed. Ex: If an object is holding some non-java resource such as a file, then you might want to make sure these resources are freed before an object is destroyed. ⚫ Tohandle such situations, Java provides a mechanism called finalization. ⚫ The finalize( ) method has this general form: protected void finalize( ){ // finalization code here }