CST 205 –OBJECT ORIENTED PROGRAMMIMG USING JAVA
MODULE _I
Nusrath P K
Asst Prof Department of CSE
The Java Buzzwords
Java buzzwords refer to the key concepts, principles, and features of the Java programming
• Simple
• Secure
• Platform-Independent
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
Simple
Java was designed to be easy for the professional programmer to learn and use effectively.
Secure:
Java provides a secure environment for developing and running applications, with features
like bytecode verification, access control, and an exception-handling mechanism.
Platform-Independent:
Java is designed to be platform-independent, meaning Java code can run on any device that
has the Java Virtual Machine (JVM). This is often summarized as "Write Once, Run
Anywhere" (WORA).
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
Object-Oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Robust
Java emphasizes reliability with
o Strong memory management.
o Automatic garbage collection which runs on the Java Virtual Machine to remove
objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java.
Multithreaded
Multithreading in Java refers to the concurrent execution of multiple threads within a Java
program. A thread is the smallest unit of a program that can be executed independently and
multithreading allows you to write programs that can perform multiple tasks simultaneously.
Architecture-Neutral
Java's byte code is architecture-neutral, meaning it is not dependent on a specific hardware
or operating system architecture.
Interpreted and High Performance
Java is both compiled and interpreted. The source code is compiled into bytecode,
which is then interpreted by the JVM.
Java achieves high performance through the Just-In-Time (JIT) compiler, which
optimizes byte code into machine code at runtime
Distributed
Java supports distributed computing, which allows programs to work over a network. This
feature of Java allows to access files by calling the methods from any machine on the
internet.
Dynamic
Java is highly dynamic in nature as it can adapt to its evolving environment. It supports the
dynamic loading of classes. It means classes are loaded on demand.
***************************************************************************
JVM (Java Virtual Machine):
Purpose: The core of Java, JVM loads, verifies, and runs Java bytecode.
It provides a runtime environment for Java applications to run on
different platforms and operating systems.
Functionality: It reads and interprets the bytecode (compiled Java code)
and translates it into machine code that the operating system can execute.
Platform Independence: JVM allows Java programs to be platform-
independent, as the same bytecode can run on any operating system that
has a JVM implementation.
There are three main subsystems in JVM Architecture:
1. ClassLoader
2. Memory Area
3. Execution Engine
ClassLoader
It is the component of JVM Architecture that loads classes in memory. Every
JVM consists of a ClassLoader. Three built-in classloaders in Java are:
1. Bootstrap ClassLoader
2. Extension ClassLoader.
3. System/Application ClassLoader
JVM Memory area
1. Method Area– It stores the structure of each class .
2. Heap– Heap is the runtime area where object allocation takes place.
3. Stacks– Stacks store the partial results and local variables of a program.
4. PC Registers – It stores the address of the currently executing JVM
instruction.
5. Native Method Stacks – It includes all the native methods required in any
application. It is not written in java.
Execution Engine
It is the component of JVM that reads data from memory locations and executes
the instructions. It has three major components namely a virtual processor, an
interpreter, and a JIT compiler.
1. Virtual Processor
2. Interpreter: Read the bytecode stream then execute the instructions.
3. Just-In-Time (JIT) compiler: It improves performance. JIT is part of the
Java Virtual Machine. It increases the execution time
2. JRE (Java Runtime Environment):
Purpose: The JRE provides the runtime environment necessary to run
Java applications. It includes the JVM and libraries that support the
execution of Java applications.
Components:
o JVM:
o Java Class Libraries: A set of pre-written classes and functions
that are required to run Java programs.
JVM runs inside the JRE environment. JRE contains class libraries, Java
Virtual Machine and other files other than development tools like
compiler and debugger.
3. JDK (Java Development Kit):
Purpose: The JDK is a complete software development kit for Java. It
includes everything you need to develop Java applications.
Components:
o JRE: As described above, the JRE is included in the JDK.
o Development Tools: Tools like javac (Java compiler), javadoc
(documentation generator), jdb (debugger), and others necessary
for Java development.
Usage: The JDK is what needed to write, compile, and debug Java
programs. It’s used by developers to create Java applications.
*********************************************************
Bytecode
Bytecode in Java is an intermediate, platform-independent code that is
generated by the Java compiler (javac) after a Java program is compiled.
This bytecode is executed by the Java Virtual Machine (JVM).
1. Intermediate Representation:
o When you compile a .java file, the Java compiler translates the
human-readable source code into bytecode, which is stored in
.class files.
o This bytecode is a set of instructions that the JVM can understand
and execute. It’s an intermediate step between the high-level Java
code and the machine code that the CPU can execute.
2. Platform Independence:
o One of Java's key features is its platform independence, often
summarized as "Write Once, Run Anywhere" (WORA).
This is made possible by bytecode.
o Since bytecode is platform-independent, the same .class file can
run on any device that has a JVM, regardless of the underlying
operating system or hardware architecture.
The JVM interprets or compiles (using Just-In-Time (JIT) compilation) the
bytecode into native machine code
The JVM’s role is to provide a runtime environment that can execute bytecode
and translate
Portability:
Because bytecode is not specific to machine architecture, it is portable
across different platforms.
Security:
Bytecode includes features that allow the JVM to enforce runtime checks,
such as array bounds checking and type safety, enhancing the security of
Java applications.
public class HelloWorld
{
public static void main(String[] args)
{
[Link]("Hello, World!");
}}
After compiling this code, the [Link] file will contain bytecode
that corresponds to the high-level instructions given in the source code.
**********************************************************
Java program structure
Simple java program :
// first java program
import [Link].*;
public class Example
{
public static void main(String[] args)
{
[Link]("This is a simple Java program.");
}
Documentation Section
The documentation section in the structure of a Java program provides essential
details about the program.
To include these details, programmers typically use comments.
Comments are non-executable parts of a program.
A compiler does not execute a comment.
It is used to improve the readability of the code.
Writing comments is a good practice as it improves the documentation of the code.
There are three different types of comments- single-line, multi-line, and
documentation comments.
Single line comment- It is a comment that starts with // and is only used for a single
line.
//Single-line comment
Multi line comment- It is a comment that starts with /* and ends with */ and is used
when more than one line has to be enclosed as comments.
/* Multiline comment
in Java */
Documentation comment- It is a comment that starts with /** and ends with */
/** Documentation comment */
Import Statements:
Import statements are used to import other Java classes and packages into program
The program imports all classes from [Link]
class Example {
The class declaration is the core of a Java program.
Every Java program must have at least one class, which is declared using the class
keyword.
Syntax: public class ClassName { ... }
The name of the class must match the name of the file (e.g., [Link] should
contain public class Example).
Here Example is an identifier that is the name of the class.
The entire class definition, including all of its members, will be between the opening
curly brace ({) and the closing curly brace (}).
Main Method
Syntax: public static void main(String[] args) { ... } this is the line at which the
program will begin executing.
All Java applications begin execution by calling main( ).
main( ) must be declared as public, since it must be called by code outside of its class
when the program is started.
The keyword static allows main( ) to be accessed without creating an instance of the
class. It is necessary since main( ) is called by the Java Virtual Machine before any
objects are made.
The keyword void simply tells the compiler that main( ) does not return a value.
In main( ), there is only one parameter. String args[ ] declares a parameter named
args, which is an array of instances of the class String.
In this case, args receives any command-line arguments present when the program is
executed.
{. This signals the start of main( )’s body. All of the code that comprises a method
will occur between the method’s opening curly brace and its closing curly brace.
main( ) is simply a starting place for your program.
A complex program will have dozens of classes, only one of which will need to have
a main( ) method to get things started.
[Link]("This is a simple Java program.");
It occurs inside main( ).
This line outputs the string "This is a simple Java program."
println( ) displays the string which is passed to it.
System is a predefined class that provides access to the system, and out is the
output stream that is connected to the console.
println( ) statement ends with a semicolon.
All statements in Java end with a semicolon.
The reason that the other lines in the program do not end in a semicolon is that
they are not, technically, statements.
The first } in the program ends main( ),
and the last } ends the Example class definition
In a Java program, the variables and constants are defined just after the class
definition.
class Example //class definition
//variable
int id;
id = 100; // this assigns num the value 100
void display()
[Link]("Welcome to javatpoint");
}}
A method is a collection of statements that perform a specific task.
Method names typically begin with a lowercase letter.
void display() is a method , void if does not return any value.
If there are no parameters, you must put empty parentheses ().
**************************************************************************
Garbage collection
Garbage collection in Java is the process by which Java programs perform
automatic memory management.
Java programs compile to bytecode that can be run on a Java Virtual Machine.
When Java programs run on the JVM, objects are created on the heap, which is a
portion of memory dedicated to the program.
Garbage collection is the process of looking at heap memory, identifying which
objects are in use and which are not, and deleting the unused objects.
The garbage collector finds these unused objects and deletes them to free up
memory.
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
It is automatically done by the garbage collector(a part of JVM)
There are generally three ways to make an object eligible for garbage collection.
o By nulling the reference
o By assigning a reference to another
o By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;
now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();
Finalization
Just before destroying an object, Garbage Collector calls finalize() to perform cleanup
activities.
Once finalize() method completes, Garbage Collector destroys that object.
finalize() syntax:
protected void finalize()
The finalize() method is never invoked more than once for any object.
[Link]()
The gc() method is used to invoke the garbage collector to perform cleanup processing.
public class GarbageCollection
{
public void finalize()
{
[Link] ("Garbage Collection performed by JVM");
}
public static void main (String args[])
{
GarbageCollection s1 = new GarbageCollection ();
GarbageCollection s2 = new GarbageCollection ();
s1 = null;
s2 = null;
[Link]();
}
}
***************************************************************************
Lexical Issues
Java programs are a collection of whitespace, identifiers, literals, comments,
operators, separators, and keywords.
Lexical issues refer to problems related to the lexical structure or rules of the
programming language.
Whitespace
In Java, whitespace is a space, tab, or newline.
Incorrectly placing white spaces in literals or between tokens can lead to errors.
For example, int a = 10 ; is valid, but int a = 1 0; will cause a compilation error.
Identifiers
Identifiers are names given to elements like variables, methods, classes, etc.
Identifiers must begin with a letter, dollar sign ($), or underscore (_), and they cannot
be the same as any of Java's reserved keywords.
Also, Java is case-sensitive, so Variable and variable would be considered different
identifiers.
Literals
Literals represent fixed values in the code, such as 10 (an integer), "Hello" (a string),
true (a boolean), etc.
Misuse or incorrect representation of literals (e.g., missing quotes around a string,
using a floating-point literal in an integer context) can lead to compilation errors.
Comments
Comments are used to document the code and are ignored by the compiler.
They can be single-line (//) or multi-line (/* ... */).
Forgetting to close a multi-line comment (*/) can cause the rest of the code to be
treated as a comment, leading to unexpected compilation errors.
Separators
Separators are symbols used to define the structure of the program, like {}, [], (), ;,
etc.
Missing or extra separators can lead to syntax errors.
For instance, forgetting a semicolon (;) at the end of a statement will cause a
compilation error.
Keywords
Keywords are reserved words in Java that have a predefined meaning in the language,
such as class, public, static, etc.
Using a keyword as an identifier (e.g., variable name) is not allowed and will cause a
compilation error.
*************************************************************
Java Applets
An applet is a special kind of Java program that is designed to be transmitted over the
Internet and automatically executed by a Java-compatible web browser.
If the user clicks a link that contains an applet, the applet will be automatically
downloaded and run in the browser.
Applets are intended to be small programs.
They are typically used to display data provided by the server, handle user input, or
provide simple functions, such as a loan calculator, that execute locally, rather than on
the server.
The applets are used to provide interactive features to web applications.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed
Any applet in Java is a class that extends the [Link] class.
import [Link].*;
import [Link].*;
public class newClass extends Applet
{
public void paint (Graphics g)
{
[Link]("Hello World", 300, 150);
}
}
<!DOCTYPE html>
<html>
<head>
<title>HTML applet Tag</title>
</head>
<body>
<applet code = "[Link]" width = "300" height = "200"></applet>
</body>
</html>