J Dr. K.
MAKESH BABU,
A ASSISTANT PROFESSOR IN
V
COMPUTER APPLICATIONS
BISHOP HEBER COLLEGE
A TRICHY, TAMILNADU, INDIA
UNIT I
Introduction: Review of Object Oriented concepts – History of
Java – Java buzzwords – JVM architecture – Data types -
Variables - Scope and life time of variables - arrays - operators
– control statements - type conversion and casting - simple
java program - constructors - methods - Static block - Static
Data – Static Method String and String Buffer Classes
JAVA BUZZWORDS
A buzzword is a word or phrase, new or already existing,
that becomes popular for a period of time
simple.
Secure.
Portable.
Object-oriented.
Robust.
Architecture-neutral (or) platform independent.
Multi-threaded.
Interpreted.
JAVA ARCHITECTURE
JVM (java virtual machine) is an abstract machine.
It is a specification that provides runtime environment in which
java bytecode can be executed.
The JVM consists of three distinct components:
class loader.
Runtime memory/data area.
Execution engine.
1. Class loader
Class loader is a subsystem of JVM which is used to load class files.
Whenever we run the java program, it is loaded first by the classloader.
There are three built-in classloaders in java.
Bootstrap class loader: this is the first classloader which is the super class of
extension classloader. It loads the rt.Jar file which contains all class files of java
Extension classloader: this is the child classloader of bootstrap and parent
classloader of system classloader. It loades the jar files located
inside $JAVA_HOME/jre /lib/ext directory.
System/application classloader: this is the child classloader of extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory
2. Class(method) area
class(method) area stores per-class structures such as the runtime
constant pool, field and method data, the code for methods.
3. heap it is the runtime data area in which objects are allocated.
4. stack- java stack stores frames. It holds local variables and partial
results, and plays a part in method invocation and return.
5) program counter register
PC (program counter) register contains the address of the java virtual
machine instruction currently being executed.
6) Native Method Stack
It contains all the native methods used in the application.
7) Execution engine
a. A virtual processor
b. interpreter: read bytecode stream then execute the instructions.
c. Just-in-time(JIT) compiler: it is used to improve the performance.
JIT compiles parts of the byte code. that have similar functionality at the
same time, and hence reduces the amount of time needed for compilation.
8) Java Native Interface
java native interface (JNI) is a framework which provides an interface to
communicate with another application written in another language like C,
C++, assembly etc. Java uses JNI framework to send output to the console
or interact with OS libraries.
DATA TYPES IN JAVA
Data types specify the different sizes and values that can be stored in the
variable.
There are two types of data types in java:
Primitive data types: the primitive data types include boolean, char, byte,
short, int, long, float and double.
Non-primitive data types: the non-primitive data types
include classes, interfaces, and arrays.
JAVA PRIMITIVE DATA TYPES
Boolean data type
Byte data type
Char data type
Short data type
Int data type
Long data type
Float data type
Double data type
NON-PRIMITIVE DATA TYPES IN JAVA
Class
Interface
Arrays
Enum
JAVA VARIABLE
Java variables and literals are where variables are used to store data values,
while literals are used to represent fixed values in code.
Java literal is a fixed value that appears directly in the code, and its value
cannot be changed during program execution.
Java 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.
Instancevariables 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
keyword ‘new’ and destroyed when the object is destroyed.
The instance variables are visible for all methods, constructors and block
in the class. Normally, it is recommended to make these variables private
(access level).
Instancevariables can be accessed directly by calling the variable name
inside the class
Classvariables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
Therewould only be one copy of each class variable per class, regardless of
how many objects are created from it.
Static
variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.
Staticvariables are stored in the static memory. It is rare to use static
variables other than declared final and used as either public or private
constants.
Staticvariables are created when the program starts and destroyed when the
program stops.
SCOPE OF A VARIABLE
Scope of a variable refers to in which areas or sections of a program can the
variable be accessed.
and
lifetime of a variable refers to how long the variable stays alive in
memory.
Instance variable.
A variablewhich is declared inside a class and outside all the methods and
blocks is an instance variable.
General
scope of an instance variable is throughout the class except in static
methods.
Lifetime of an instance variable is until the object stays in memory
class variable
A variable which is declared inside a class, outside all the blocks and is
marked static is known as a class variable.
General scope of a class variable is throughout the class and the lifetime of a
class variable is until the end of the program or as long as the class is loaded
in memory.
Local variable
Scope of a local variable is within the block in which it is declared and
the lifetime of a local variable is until the control leaves the block in which it
is declared.
Java divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
CONTROL FLOW STATEMENTS.
Java compiler executes the code from top to bottom. Java provides statements
that can be used to control the flow of java code. Such statements are called
control flow statements.
Java provides three types of control flow statements.
1. Decision making statements
If statements
Switch statement
2. Loop statements
Do while loop
While loop
For loop, For-each loop
3. Jump statements
Break statement
Continue statement
JAVA ARRAYS
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
To declare an array, define the variable type with square brackets:
String[] cars;
String[] cars = {"volvo", "bmw", "ford", "mazda"};
Int[] mynum = {10, 20, 30, 40};
String[] cars = {"volvo", "bmw", "ford", "mazda"};
System.Out.Println(cars[0]); output volvo
String[] cars = {"volvo", "BMW", "ford", "mazda"}; system.Out.Println(cars.Length);
// outputs 4
TYPE CASTING IN JAVA
Type casting in Java is a fundamental concept that allows developers to
convert data from one data type to another.
It is essential for handling data in various situations, especially when dealing
with different types of variables, expressions, and methods.
In Java, type casting is a method or process that converts a data type into
another data type in both ways manually and automatically.
TYPES OF DATA CONVERSION
Widening Conversion (Implicit) Automatic
No explicit notation is required.
Conversion from a smaller data type to a larger data type is allowed.
No risk of data loss.
Narrowing Conversion (Explicit) Manually
Requires explicit notation using parentheses and casting.
Conversion from a larger data type to a smaller data type is allowed.
Risk of data loss due to truncation.
public class Main { public static void main(String[] args)
{ int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9 System.out.println(myDouble); //
Outputs 9.0 } }
public class Main { public static void main(String[] args)
{ double myDouble = 9.78d;
int myInt = (int) myDouble;
// Manual casting: double to int System.out.println(myDouble); // Outputs
9.78 System.out.println(myInt); // Outputs 9 } }
STRUCTURE OF A JAVA PROGRAM
A typical structure of a Java program contains the following elements:
Documentation Section
Package Declaration
Import Statements
Interface Section
Class Definition
Class Variables and Variables
Main Method Class
Methods and Behaviours
JAVA CLASS AND OBJECTS
A class contains data members and the methods that act upon those
data members.
A class is a blueprint for the object. Before we create an object, we
first need to define the class.
General form of a class
class Classname
{ type 1 dataname;
method name (arg )
psvm (String arg[])
{ }}
CLASS AND OBJECT EXAMPLE (WITH VARIABLE)
class Display
{ int a = 100;}
class Maintest
{ public static void main (String args[])
{
Display d = new Display ();
int x = d.a;
System.out.println(x);
}
}
CLASS PROGRAM WITH NO RETURN TYPE NO ARGUMENT
class Noargs
{ in k = 10;
void print()
{ System.out.println(k);}}
class Mainprg
{ public static void main (String arg[])
{ Noargs n = new Noargs();
n.print(); }
NO RETURNTYPE WITH ONE OR TWO ARGUMENTS
class Argsprg
{ Void disp(String s1)
{ System.out.println(“hai”+s1); }
}
class Argmain
{
public static void main (String arg[])
{ Argsprg r = new Argsprg();
r. disp(“welcome”);}
RETURN TYPE WITH ARGUMENTS
class Arg
{ int x = 10;
int disp();
{ return x; }}
class Mainarg
{ public static void main(String arg[ ])
{ Arg s = new Arg( );
System.out.println(s.disp()) ; }
}
CONSTRUCTOR
Constructor is a specialized method, that is used to initialize methods.
The constructor is called when an object is created. The name of constructor
method name should be always same as the name of the class and it has no
return type and void. It is generally declared as public.
Class Cons
{ Cons ()
{ System.out.println(“Constructor”);}
Class Maincons
{ public static void main (String args[])
{ Cons a = new Cons();
System.out.println(a.cons());}}
CONSTRUCTOR EXAMPLE WITH ARGS
class Cons
{Cons (int x)
{
System.out.println(x); }}
class Maincons
{ public static void main (String args[])
{ Cons a = new Cons();}}
CONSTRUCTOR OVERLOADING
class Area
{ Area (int length, int breath)
{ int a = length * breath;
System.out.println(“Area of a rectangle”+a); }
Area (int side)
{ int b = side * side;
System.out.println(“Area of a square”+b); }}
class Maincons
{ public static void main (String args[])
{ Area a = new Area(10,15); Area b = new Area(10);}}
COPY CONSTRUCTOR
Create a duplicate of an existing object of a class.
To create this there is a special type of constructor known as copy
constructor.
This constructor can take only one parameter which is a reference to an
object of the same class
EXAMPLE FOR COPY CONSTRUCTOR
class Distance
{ int x,y;
Distance (int x, int y)
{this.x = x; this.y = y;}
Distance ( Distance z)
{ this.x = p.x; this.y = p.y;)
DistanceOrigin ()
{ return Math.sqrt(x*x+y*y);}
}
Class Maindistance
{ Public satic void main (String arg[])
{ Distance p = new Distance (4,3);
System.out.println(p.Distanceorigin());
Distance q = new distance(p);
System.out.println(q.Distanceorigin ());}
}
“this” Key word
The this keyword refers to the current object of the class in
which it is used.
In Java, this is a reference variable that refers to the current
object.
STATIC DATA MEMBER
A static variable is defined for a class itself.
Its value does not vary from object to object.
There will be only one copy of a static variable and all objects of
the class will share it.
Due to this reason, static variable are known as class variable.
A static variable is declared by preceding its usual declaration with
the static key word
Eg. static datatype variablename; static int count;
EXAMPLE FOR STATIC DATA MEMBER
Class St
{ static int s1 = 25; int s2 = 100; }
Class Mainst
{
public static void main (String arg[])
{ System.out.println(st.s1); // no need to create object for static
variable
St sn = new St();
System.out.println(sn.s2);}
}
STATIC METHODS
A static method is defined for the class itself. .(class methods)
It is not necessary to create an object of a class in order to invoke
a static method defined in it..
Static methods have access to class variables (static variables) without using
the class’s object (instance).
Eg. classname.staticmethodname(arg);
Or objectname.staticmethodname(arg);
Declaring static methods egs. Static returntype
methodname(paremeter){}
EXAMPLE FOR STATIC METHODS
Class Stm
{ int x = 10; int y = 20;
static { System.out.println(y);
System.out.println(“static block”); y -= y+x;
System.out.prinlnt(y); }
Class Mainstm
{ public static void main (String arg[])
{ Stm s1 = new Stm();
System.out.println(s1.x); }
} Output : 20, static block , 30,
StringBuffer to concatenate strings
Stringbuffer is a class in java that represents a mutable sequence of
characters. It provides an alternative to the immutable string class, allowing
you to modify the contents of a string without creating a new object every
time.
Public class stringbufferexample
{
Public static void main(string[] args)
{ stringbuffer sb = new stringbuffer(); sb.Append("hello");
Sb.Append(" ");
Sb.Append("world");
String message = sb.Tostring();
System.Out.Println(message); }
}
Finalize method
The java runtime provides a special utility known as
Garbage collecting system.
This system checks the code quite often and removes those
objects which are no more referred by the code. But this
mechanism does not remove the non object resources.
So we must write code finazlize() method for removing
such non object resources.