0% found this document useful (0 votes)
6 views167 pages

OOP Java - Reference - Student

Uploaded by

akashkp2144
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views167 pages

OOP Java - Reference - Student

Uploaded by

akashkp2144
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 167

Java Programming

Chapter
Introduction to Java
Java History
• Java is an Object-Oriented programming language
• developed by James Gosling in the early 1990s.
• James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
• The small team of sun engineers called Green Team.
• The team initiated to develop a language for digital devices such as set-top boxes, television, etc.
• Originally C++ was considered to be used in the project but the idea was rejected for several
• Firstly, it was called "Greentalk" , the file extension was .gt.
• After that, it was called Oak and was developed as a part of the Green project.
• In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
Features
• Simple
✓ Java is a simple programming language
✓ because it has to work on electronic devices, where less memory is available.
✓ all, the difficult concepts of C and C been omitted in Java.
✓ For example, the concept of pointers eliminated from Java.
✓ Next, JavaSoft (the team who developed Java is called with this name) people maintained the same
syntax of C
and C++ in Java, so that a programmer who knows C or C++ will find Java already familiar
✓ a cleaned-up version of the syntax for C++.
✓ There is no need for header files, pointer arithmetic (or even a pointer syntax), structures, unions,
operator overloading, virtual base classes, and so on.
✓ For example, the syntax of the switch
✓ statement is unchanged in Java , if user know C++, then user will find the transition to the Java syntax
easy.
✓ Another aspect of being simple is being small. One of the goals of Java is to enable the construction of
software
that can run stand-alone in small machines.
✓ The size of the basic interpreter and class support is about 40K bytes; adding the basic standard
libraries and thread support adds an additional 175K
Object-oriented:

✓ Java is an object-oriented programming language.


✓ This means Java programs use objects and classes
✓ An object is anything that really exists in the world and can be distinguished from others.
✓ Everything that we see physically will come into this definition, for example, every human being, a book,
a tree, and so on.
✓ Now, every object has properties and exhibits certain behavior.
✓ Example of a dog. It got properties like name, height, color, age, etc. These properties are represented by
variables.
✓ Now, the object dog will have some actions like running, barking, eating, etc.
✓ These actions are represented by various methods (functions) in our programming. In programming, various
tasks are done by methods only.
✓ So, we can conclude that objects contain variables and methods.
✓ Simply stated, object-oriented design is a technique for programming that focuses on the data (= objects)
and on the interfaces to that object.
• A group of objects exhibiting same behavior (properties + actions) will come under the
same group called a class.
• A class represents a group name given to several objects. For example, take the dogs:
Pinky, Nancy, Tom, and Subbu.
All these four dogs exhibit same behavior and hence belong to the same group, called
dog. So dog is the class name, which contains four objects. In other words, we could define
a class as a model or a blueprint for creating the objects.
• We write the characteristics of the objects in the class: 'dog'. This means, a class can be
used as a model in creation of objects. So, just like objects, a class also contains
properties and actions, i.e. variables and methods
Distributed:

• Information is distributed on various computers on a network.


• Using Java, we can write programs, which capture information and distribute it to the clients.
• This is possible because Java can handle the protocols like TCP/IP and UDP.
• networking capabilities of Java to be both strong and easy to use.
• It makes onerous tasks like opening a socket connection simple .
• An elegant mechanism, called servlets, makes server-side processing in Java extremely
efficient.
• Many popular web servers support servlets.
Robust:
• Java programs are strong and they don't crash easily like a C or C++ program.
• There are two reasons for this. Firstly, Java has got excellent inbuilt exception handling
features.
• An exception is an error that occurs at run time. If an exception occurs, the program
terminates abruptly giving rise
• to problems like loss of data.
• Overcoming such problems is called exception handling.
• This means that even though an exception occurs in a Java program, no harm will happen.
• Another reason is excellent memory management features .
• Variables will be allocated and deallocated and it is taken care by JVM.
• Java puts a lot of emphasis on early checking for possible problems, dynamic (run-time)
checking, and eliminating situations that are error- prone.
• The single biggest difference between Java and C/C++ is that Java has a pointer model that
eliminates the possibility of overwriting memory and corrupting data
Secure:
✓Security problems like eavesdropping, tampering,
impersonation, and virus be threats eliminated or minimized
by using Java on Internet
✓virus-free, tamper-free systems.
✓digitally signed classes
✓With a signed class, you can be sure of who wrote it.
✓Any time you trust the author of the class, the class can be
allowed more privileges on your machine.
System independence:
✓Java's byte code is not machine dependent.
✓It can be run machine with on a
any processor and any operating system
✓The compiler generates an architecture-neutral object file format—
✓The compiled code is executable on many processors, given the
presence of the Java run time system.
✓The Java compiler does this by generating bytecode
instructions which have nothing to do with a particular computer
architecture.
✓Rather, they are designed to be both easy to interpret on any machine
and easily translated into native machine code
✓developing a bytecode instruction set that works well on today's most
common computer architectures.
✓And the codes have been designed to translate easily into actual
machine instructions
portability:
• If a program yields the same result on every machine, then that programs are portable
• implementation-dependent” aspects of the specification.
• The sizes of the primitive data types are specified, as is the behavior of arithmetic on them
• for example, an int in Java is always a 32-bit integer. In C/C++, int can mean a 16-bit integer,
as many bytes as a short int and cannot have more
• a 32-bit integer, or any other size that the compiler vendor likes. The only restriction is that
the int type must have at least bytes than a long int.
• Having a fixed size for number types eliminates a major porting headache.
• Binary data is stored and transmitted in a fixed format, eliminating the “big endian/little
endian” confusion.
• Strings are saved in a standard Unicode format
Interpreted:
✓ Java programs are compiled to generate the byte code.

✓ This byte code downloaded and can interpreted by the interpreter in JVM
✓ The Java interpreter can execute Java bytecodes directly on any machine to which the
interpreter has been ported.
High Performance:
✓ introduced JIT (Just In Time) compiler, which enhances execution.
✓So now in JVM, both the speed interpreter and JIT Compiler work together
✓If you use an interpreter to execute the bytecodes, then no “high
performance”
✓However, on many platforms, there is also another form of compilation,
the just- in-time (JIT) compilers.

✓ These work by compiling the bytecodes into native code once, caching the
results, and then calling them again if needed.
✓This approach speeds up commonly used code tremendously since one has
to do the interpretation only once.
✓Although still slightly slower than a true native code compiler, a just-in-
time compiler can give you a 10- or even 20-fold speedup for some
programs and will almost always be significantly faster than the Java
interpreter.
✓This technology is being improved continuously and may eventually yield
results that cannot be matched by traditional compilation systems.
✓For example, a just- in-time compiler can monitor which code is executed
frequently and optimize just that code for speed.
Multithreaded:
✓ A run the program thread represents an individual process to execute a group of
✓ statement JVM uses several threads to execute different blocks of code. Creating
multiple multithreaded’.
✓ benefits of multithreading are better interactive responsiveness and real-
time behavior.
✓ Threads in Java also have the capacity to take advantage of
multiprocessor system
Scalability:
Java platform can be implemented on a wide levels of resources range of computers with -
from embedded devices to mainframe Java is compact and platform computers.

Dynamic:
✓ Java is a more dynamic language than C or C++.
✓ designed to adapt to an evolving environment.
✓ Libraries can freely add new methods and instance variables without any effect on their
clients.
✓ In Java, finding out run time type information is straightforward
✓ Run Time Information is a feature that enables retrieval of the type of an object during
run time.
✓ animation can be done using applets .
✓ Run Time Information
• Determining the type of object at run time not only reduces error but also results in
robustness.
• It is also useful before typecasting any object into another type to avoid run time
exception.
Java’s Magic: Bytecode
• The key that allows Java to solve both the security and the portability problems just
described is that the output of a Java compiler is not executable code.
• bytecode.
• Bytecode is a highly optimized set of instructions designed to be executed by the Java
run-time system, which is called the Java Virtual Machine (JVM).
• In essence, the original JVM was designed as an interpreter for bytecode.
• However, the fact that a Java program is executed by the JVM helps solve the major
problems associated with web-based programs.
• Translating a Java program into bytecode makes it much easier to run a program in a
wide variety of environments because only the JVM needs to be implemented for
each platform.
• Once the run-time package exists for a given system, any Java program can run on it.
• although the details of the JVM will differ from platform to platform, all understand
the same Java bytecode.
• If a Java program were compiled to native code, then different versions of the same
program would have to exist for each type of CPU connected to the Internet.
• This is, of course, not a feasible solution. Thus, the execution of bytecode by the
JVM is the easiest way to create truly portable programs. The fact that a Java
program is executed by the JVM also helps to make it secure.
Fundamentals of Object Oriented Programming
• The major objective of object-oriented approach is to
eliminate some of the flaws encountered in the procedural
approach OOP treats data as a critical element in the program
development and does not allow it to flow freely around the
system.
• it ties data more closely to the functions that operate
on it and protects it from unintentional modification by other
functions.
• OOP allows us to decompose a problem into a
number of entities called Objects and then build data and
functions (known as methods in Java) around these entities.
The combination of data and methods make up an object
• Object-oriented programming is an approach that provides a way of modularizing
programs by creating partitioned memory area for both data and functions that can be
used as templates for creating copies of such modules on demand.
Features of OOPs
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as Objects
3. Data structures are designed such that they characterize the objects.
4. Methods that operate on the data of an object are tied together in the
data structure
5. Data is hidden and cannot be accessed by external functions.
6. Objects may communicate with each other through methods.
7. New data and methods can be easily added whenever necessary.
8. Follows bottom-up approach in program design
Basic Concepts of Object Oriented
Programming
Objects & Classes
✓ Program objects should be chosen such that they match closely with the real-world objects.
✓ When a program is executed, the objects interact by sending messages to one another.
✓ For example, 'customer and 'account are two objects in a banking program, then the customer
object may send a message to the account object requesting for the balance.
✓ Each object contains data and code to manipulate the data.
✓ Objects can interact without having to know the details of each other's data or code
✓ The entire set of data and code of an object can be made a user-defined data type using the
concept of a class.
✓ A class may be thought of as a 'data type' and an object as a 'variable' of that data type.
✓ Once a class has been defined, we can create any number of objects belonging to that class.
✓ Each object is associated with the data of type class with which they are created.
✓ A class is thus a collection of objects of similar
type.
✓ For example, mango, apple and orange are members of the class fruit. Classes are user-defined
data types and behave like the built-in types of a programming language.
✓ For example, the syntax used to create an object is no different than the syntax used to create
an integer object in C.
✓ If fruit has been defined as a class, then the statement

✓ fruit mango;
will create an object mango belonging to the class fruit.
Abstraction (achieved through abstract class & interfaces)
• For example, people do not think of a car as a set of tens of thousands of individual parts.
• They think of it as a well-defined object with its own unique behavior.
• This abstraction allows people to use a car to drive to the grocery store without being
overwhelmed by the complexity of the parts that form the car.
• They can ignore the details of how the engine, transmission, and braking systems work , free to
utilize the object as a whole.
• A powerful way to manage abstraction is through the use of hierarchical classifications.
• This allows you to layer the semantics of complex systems, breaking them into more manageable
pieces.
• From the outside, the car is a single object.
• Once inside, you see that the car consists of several subsystems: steering, brakes, sound system,
seat belts, heating, cellular phone, and so on.
• In turn, each of these subsystems is made up of more specialized units. For instance, the sound
system consists of a radio, a CD player, and/or a tape or MP3 player.
• The point is that you manage the complexity of the car (or any other complex system) through the
use of hierarchical abstractions.
• Hierarchical abstractions of complex systems can also be applied to computer programs. The data
from a traditional process-oriented program can be transformed by abstraction into its component
objects.
• A sequence of process steps can become a collection of messages between these objects
• Abstraction is Just Hiding the complex things behind a particular Procedure to
make the procedure look simple.
Example:
• Monitor ON/OFF::--The user doesn't need to know much about all the chips
functioning that happens when Monitor is switched ON or OFF.
• All he needs to know is On Function ON-Monitor is On and on function OFF-
Monitor is off...
• Or Better Look for a car--Everyone Knows that There's a special Gear machine
Which changes the gear,nobody bother to know what all functionality
undergoes for a gear to change
• avoiding unwanted implementations to prevent Complexity
• achieved by making class abstract having one or more methods abstract.
Which is nothing but essential characteristic which should be implemented by
the class extending.
• Abstraction can be achieved through abstract class and interface
• Hides internal implementation , creates skeleton of what is required for the
enity.
Encapsulation
✓ mechanism that binds together code and the data it manipulates, and keeps both safe from
outside interference and misuse.
✓ protective wrapper that prevents the code and data from being arbitrarily accessed by other
code defined outside the wrapper.
✓ Access to the code and data inside the wrapper is tightly controlled through a well-defined
interface.

Example:
✓ consider the automatic transmission on an automobile.
✓ It encapsulates hundreds of bits of information about your engine, such as how much you are
accelerating, the pitch of the surface you are on, and the position of the shift lever.
✓ You, as the user, have only one method of affecting this complex encapsulation: by moving the
gear-shift lever.
✓ You can’t affect the transmission by using the turn signal or windshield wipers,
✓ for example. Thus, the gear-shift lever is a well-defined (indeed, unique) interface to the
transmission.
✓ Further, what occurs inside the transmission does not affect objects outside the transmission.
✓ For example, shifting gears does not turn on the headlights! Because an automatic transmission is
encapsulated, dozens of car manufacturers can implement one in any way they please.
✓ However, from the driver’s point of view, they all work the same. This same idea can be applied to
programming.
✓ The power of encapsulated code is that everyone knows how to access it and thus can use it
regardless of the implementation details—and without fear of unexpected side effects
✓the basis of encapsulation is the class.
✓ A class defines the structure and behavior (data and
code) that will be shared by a set of objects.
✓ Each object of a given class contains the structure and
behavior defined by the class
✓. For this reason, objects are sometimes referred to as
instances of a class.
✓Thus, a class is a logical construct; an object has
physical reality.
✓When you create a class, you will specify the code and
data that constitute that class.
✓Collectively, these elements are called members of the
class.
✓Hides data from external world , protect data within
class and exposes method to the world
✓Specifically, the data defined by the class are referred to as
member variables or instance variables.
✓The code that operates on that data is referred to as member
methods or just methods.
✓ In properly written Java programs, the methods define how the
member variables can be used. This means that the behavior and
interface of a class are defined by the methods that operate on its
instance data.
✓ Each method or variable in a class may be marked private or
public.
✓The public interface of a class represents everything that
external users of the class need to know, or may know
✓Since the private members of a class may only be accessed by
other parts of your program through the class’ public methods,
you can ensure that no improper actions take place
• Encapsulation is restricting a user to follow a particular
procedure to access control of a particular process.
• It Just provides safety and ensures system robustness.
• Ex: We can consider The HR in a company as a person
that works on the principle of Encapsulation.i.e. we
cannot talk to other departments directly we need to
communicate through them through HR.This ensures
security and better maintenance of company's records.
• Together we can take example of a UNDER CONSTRUCTION
BUILDING..
• where we can say that things like 'no. of managers'
required,Types of Materials,
• No of workers etc as abstraction as they need to there in
every Building Construction.

• But,at the same time,Inclusion of every such field into a


CONTRACTOR which acts as a mediator between the
workers and the Building-Investor can be looked upon as
• Encapsulation.
• As,It hides all the above properties into one Entity.
class CourseRegistration{
private String student_name; In the above code, we’ve
private String course_name; created a class
public String getName(){
CourseRegistration,
return student_name; }
public void setName(String name){this.student_name=name;
where the member
}
variables student name,
public String getCourse(){ return course_name;} }
and course name are
public void setCourse(String course){ private, but we are
this.course_name=course;}} accessing it in another
public class upGrad{ class using the set name
public static void main(String[] args){ and get name functions.
CourseRegistration c=new CourseRegistration();
c.setName("mithun");
c.setCourse("Data Science");
System.out.println(c.getName());
System.out.println(c.getCourse());
}
}
Inheritance
✓is the process by which one object acquires the properties of another object.
✓ For example, a Golden Retriever is part of the classification dog, which in turn is part of the
mammal class, which is under the larger class animal.
✓ Without the use of hierarchies, each object would need to define all of its characteristics
explicitly.
✓However, by use of inheritance, an object need only define those qualities that make it
unique within its class.
✓ It can inherit its general attributes from its parent.
✓Thus, it is the inheritance mechanism that makes it possible for one object to be a specific
instance of a more general case.
✓animals in an abstract way, you would say they have some
attributes, such as size, intelligence, and type of skeletal system.
✓Animals also have certain behavioral aspects; they eat, breathe,
and sleep. This description of attributes and behavior is the class
definition for animals.
✓If you wanted to describe a more specific class of animals, such
as mammals, they would have more specific attributes, such as
type of teeth etc .
✓ This is known as a subclass of animals, where animals are
referred to as mammals’ superclass.
✓Since mammals are simply more precisely specified animals,
they inherit all of the attributes from animals.
✓A deeply inherited subclass inherits all of the attributes
from each of its ancestors in the class hierarchy
✓A new subclass inherits all of the attributes of all of its
ancestors.
Polymorphism
• Polymorphism (from Greek, meaning “many forms”) is a feature that
allows one
interface to be used for a general class of actions.
• The specific action is determined by the exact nature of the situation.
• Consider a stack (which is a last-in, first-out list).
• You might have a program that requires three types of stacks.
• One stack is used for integer values, one for floating-point values, and
one for
characters.
• The algorithm that implements each stack is the same, even though
the data being stored differs.
• In a non–object-oriented language, you would be required to create
three different sets of stack routines, with each set using different
names.
• However, because of polymorphism, in Java you can specify a general set
of stack routines that all share the same names.
• More generally, the concept of polymorphism is often expressed by the
phrase “one interface, multiple methods.”
• This means that it is possible to design a generic interface to a group of
related activities.
• This helps reduce complexity by allowing the same interface to be used to
specify a general class of action.
• It is the compiler’s job to select the specific action (that is, method) as it
applies to each situation.
• the programmer, do not need to make this selection manually.
• need only remember and utilize the general interface.

Ex: Extending the dog analogy, a dog’s sense of smell is polymorphic. If the dog
smells a cat, it will bark and run after it. If the dog smells its food, it will salivate
and run its bowl. The same sense of smell is at work in both situations. The
difference is what is being smelled, that is, the type of data being operated upon
by the dog’s nose!
• This same general concept can be implemented in Java as it applies to
methods within a Java program.
Execution of Java Program
Byte Code

• Java bytecode is the instruction set for the Java Virtual Machine.
• It acts similar to an assembler which is an alias representation of a C++ code.
• Java bytecode is the machine code in the form of a .class file.
• Resources required to run the bytecode are made available by theJava Virtual
Machine, which calls the processor to allocate the required resources.
• bytecode implementation makes Java a platform-independent language.
• This helps to add portability to Java which is lacking in languages like C or C++.
• Portability ensures that Java can be implemented on a wide array of platforms
like desktops, mobile devices, severs and many more.
JVM
• The Java Virtual Machine (JVM) is the runtime engine of the Java Platform,
which allows any program written in Java or other language compiled into Java
bytecode to run on any computer
• First of all, the .java program is converted into a .class file consisting of byte code
instructions by the java compiler.
• Remember, this java compiler is outside the JVM. Now this .class file is given to
the JVM.
• In JVM, there is a module (or program) called class loader sub system, which
performs the following functions:
• First of all, it loads the .class file into memory.
• Then it verifies whether all byte code instructions are proper or not.
• If it finds any instruction Suspicious, the execution is rejected immediately.
• If the byte instructions are proper, then it allocates necessary memory to
execute the program.
JVM
3 components of JVM
• Class loader
✓ Loading – loads class file to memory
✓ Linking – verify , prepare , resolve
verify – if class files confirm to standards, ensures that the code inside the Class object
(Class<Testing> from our example)
or interface is structurally correct.
prepare – memory is allocated for static variables & default values are
assigned
resolve – all symbolic references are replaced with actual references
- strings that can be used to retrieve the actual object.
✓ Initialization - initializing all static members of the class.
- static members are those which belongs to the class and you can access
these members without instantiating the class.
A symbolic reference is a character string that gives the name and possibly other information
about the referenced item -- enough information to uniquely identify a class, field, or
method. Thus, symbolic references to other classes give the full name of the class. Symbolic
references to the fields of other classes give the class name, field name, and field descriptor.
Symbolic references to the methods of other classes give the class name, method name, and
method descriptor.
• When a class file is loaded, it contains symbolic references to other classes
and their fields and methods.
• Dynamic linking is the process of resolving symbolic references into direct
references.
• As the JVM executes bytecodes and encounters an opcode that, for the
first time, uses a symbolic reference to another class, the virtual machine
must resolve the symbolic reference.
• The virtual machine performs two basic tasks during resolution:
- It finds the class being referenced (loading it if necessary).
- It replaces the symbolic reference with a direct reference, such as a
pointer or offset, to the class, field, or method.
if (obj.getClass() == String.class) {
// do something
}

Becomes the following bytecode:

aload_1
invokevirtual #21; //Method java/lang/Object.getClass:()Ljava/lang/Class;
ldc #25; //class java/lang/String
if_acmpne 20

In this case, the ldc operation refers to a class that is stored symbolically. When the JVM executes this opcode,
it will use the symbolic reference to identify the actual class within the current classloader, and return a
reference to the class instance.
• Runtime data areas – Method Area , Heap , Java Stacks , PC register ,
Native method Stacks .
• Execution engine - converts the byte code to machine code ,
executes the instruction .
✓ Interpreter – reads byte code and executes it one by one.
✓JIT compiler
✓JNI & Garbage collector
This memory is divided into 5 parts, called run time data areas, which
contain the data and results wnile running the program. These areas are
as follows:

Method area:
Method area is the memory block, which stores the class code, code of
the variables, and code of the methods in the Java program. (Method
means functions written in a class)

Heap:
This is the area where objects are created. Whenever JVM loads a class, a
method and a heap area are immediately created in it
Java Stacks :
✓ Method code is stored on Method area. But while running a method, it
needs some more memory to store the data and results. This memory
is allotted on Java stacks.
✓ So, data stacks are memory areas where Java methods are executed.
While executing methods, a Separate frame will be created in the Java
stack, where the method is executed.
✓ JVM uses separate thread (or process) to execute each method.

Program Counter) registers:


These are the registers (memory areas), which contain be ress of the
instructions of the methods. If there are 3 methods, 3 PC registers will be
used to track the instructions of the methods,
Native method stacks:
✓ Java methods are executed on Java stacks. Similarly, native methods rd
pe /+ functions) are executed on Native method stacks.
✓ To execute the native method native libraries (for example C/C++
header files) are required.
✓ These are located and connected to JVM by a program, called Native
method interface.
JIT compiler
• compile suitable bytecode sequences into native machine code.
• While using a JIT compiler, the hardware is able to execute the native
code, as compared to having the JVM interpret the same sequence of
bytecode repeatedly and incurring an overhead for the translation
process.
• This subsequently leads to performance gains in the execution speed,
unless the compiled methods are executed less frequently.
JNI
• Java Native Interface (JNI) is a foreign function
interface programming framework that enables Java code running in a Java
virtual machine (JVM) to call and be called by[1] native applications (programs
specific to a hardware and operating system platform) and libraries written in
other languages such as C, C++ and assembly.

• Garbage Collector
✓ Java programs perform automatic memory management.
✓ Java programs compile to bytecode that can be run on a Java Virtual Machine,
or JVM for short.
✓ When Java programs run on the JVM, objects are created on the heap, which is
a portion of memory dedicated to the program.
✓ Eventually, some objects will no longer be needed.
✓ The garbage collector finds these unused objects and deletes them to free up
memory.
Java Paradigms

• Encapsulation – wrapping of data members and member


functions
• Inheritance – object acquires all properties and behaviors
of parent object
• Information hiding – Information hiding concept restricts
direct exposure of data. Data is accessed indirectly using
safe mechanism, methods in case of programming object
• Polymorphism - the ability of any data to be processed in
more than one form. The word itself indicates the
meaningas poly means many and morphism means types.
JDK (Java Development Kit)
• is a software development environment used for developing Java applications and
applets.
• It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a
compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other
tools needed in Java development.
• Ex: Developer machine

JRE (Java Runtime Environment)


• we need an environment to make a run of our program. Henceforth, JRE stands
for “Java Runtime Environment” and may also be written as “Java RTE.”
• The Java Runtime Environment provides the minimum requirements for executing a
Java application;
• it consists of the Java Virtual Machine (JVM), core classes, and supporting files.
• Ex: Client machine
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
• Standard Edition Java Platform
• Enterprise Edition Java Platform
• Micro Edition Java Platform
Chapter
Java Program Structure
Comments
Single Line comment
• These comments are for marking a single line as a comment.
• These comments start with double slash symbol // and after this, whatever is written
till the end of
• the line is taken as a comment. For example,

Multi Line comment


• Multi line comments: These comments are used for representing several lines as
comments.
• These comments start with /* and end with */. In between /* and */, whatever is
written is
• treated as a comment. For example,
Java documentation comments
These comments start with /** and end with */. These
• comments are used to provide description for every feature in a Java program.
• This description proves helpful in the creation of a .html file called API (Application
Programming Interface) document,
• Java documentation comments should be used before every feature
Window
Window
Window
Java Libraries

Packages

Classes

Methods
import java.lang.system; System & string are classes that
belong to package java.lang
import java.lang.String;
Package name acts as a referemce to
Class First JVM
{
public static void main (String args[]) It stores Java command line arguments and is an array of
type java.lang.String class. Here, the name of the String array is args but it is
{ not fixed and user can use any name in place of it.

System.out.print(“Welcome to java”);
}
}

Main method () is the start point for


JVM to start its execution
The main() method is static so that JVM can
invoke it without instantiating the class. This
also saves the unnecessary wastage of memory
which would have been used by the object As main() method doesn’t return
declared only for calling the main() method by anything, its return type is void
the JVM.

It is made public so that JVM can invoke it from


outside the class as it is not present in the
current class.
System.out.print(“Welcome to java”);

• A method should be called by using objectname.methodname()


• . So, to call print () method, we should create an object to which print ()
method belongs.
• print() method belongs to Printstream class.
• So, we should a print () method by creating an object to Printstream class
as:
• Printstream obj.print(“welcome to Java”) ;
• But as it is not possible to create the object to PrintStream class directly, an
alternative ís given us, i.e. System. out.
• Here, System is the class name and out is a static variable/field ín System
class.
• When we call this field, a PrintStream class object will be created internally.
So, we can call the print () method as shown below :
• System.out.print("welcome to Java");
• System.out gives the PrintStream class object.
• This object, by default, represents the sta output device, i.e. the monitor.
So, the string "Welcome to Java will be sent to the monitor
public class JavaCommandLine { public static void public class JavaCommandLine {
main(String[] args) public static void main(String[] args) {
{ int n = Integer.parseInt(args[0]);
System.out.println(args[0]); System.out.println("the square of the number is
} "+n*n);

} }
}
Window
Formatting the output
If z=35

• This will display the result 35 on the monitor.


• But, this is not the proper way to display the results to the user.
• So, it is the duty of the programmer to prompt the user with a proper message, something
like this:
• Sum of two numbers = 35
• Add a string "Sum of two numbers=" before the z value in the print () method:
System.out.print("Sum of two numbers= "+z)
• Here, we are using + to join the string "Sum of two numbers=" and the numeric variable Z.
• The reason is that the print () method cannot display more than one value.
• So if two values, String like a and a numeric value need to be displayed using a single print
() method, we sh0uud Combine them using a + operator.
• If x=10 and y=25
• print(“sum of wo numbers”+ x+y) will result in 1025.
• Use braces
• print(“sum of wo numbers”+(x+y))

Println()
Display output in two separate lines
General Structure Of Java Program
Documentation Section
• The documentation section is an important section but optional for a Java program.
• It includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program.
• It improves the readability of the program. Whatever we write in the documentation section,
the Java compiler ignores the statements during the execution of the program.
• To write the statements in the documentation section, we use comments.
• The comments may be single-line, multi-line, and documentation comments.

Package Declaration
• The package declaration is optional. It is placed just after the documentation section.
In this section, we declare the package name in which the class is placed.
• Note that there can be only one package statement in a Java program.
• It must be defined before any class and interface declaration. It is necessary because
a Java class can be placed in different packages and directories based on the module
they are used. For all these classes package belongs to a single parent directory.
• We use the keyword package to declare the package name. For example:
• package student; //where student is the package name
• package com.student //where com is the root directory and studentis the subdirecto
ry
Import Statements
• The package contains the many predefined classes and interfaces.
• If we want to use any class of a particular package, we need to import that class.
• The import statement represents the class stored in the other package.
• import keyword to import the class.
• It is written before the class declaration and after the package statement.
• We use the import statement in two ways, either import a specific class or import all
classes of a particular package.
• In a Java program, we can use multiple import statements. For example:
import java.util.Scanner; //it imports the Scanner class only
import java.util.*; //it imports all the class of the java.util package
Interface Section
• It is an optional section. We can create an interface in this section if required.
• interface keyword to create an interface.
• An interface is a slightly different from the class.
• It contains only constants and method declarations. Another difference is that it cannot
be instantiated.
• use interface in classes by using the implements keyword.
• An interface can also be used with other interfaces by using the extends keyword.
• For example:
interface car
{
void start();
void stop();
}
Class Definition
• It is vital part of a Java program.
• Without the class, we cannot create any Java program.
• A Java program may conation more than one class definition. We use
the class keyword to define the class.
• The class is a blueprint of a Java program. It contains information about user-defined
methods, variables, and constants.
• Every Java program has at least one class that contains the main() method. For
example:
class Student //class definition
{
}
Class Variables and Constants
• . In a Java program, the variables and constants are defined just after
the class definition.
• The variables and constants store values of the parameters. It is used
during the execution of the program.
• We can also decide and define the scope of variables by using the
modifiers. It defines the life of the variables.
• For example:
class Student //class definition
{
String sname; //variable
int id;
double percentage;
}
Main Method Class
• define the main() method.
• It is essential for all Java programs.
• Because the execution of all Java programs starts from the main() method.
• it is an entry point of the class.
• It must be inside the class.
• Inside the main method, we create objects and call the methods. We use the following statement to
define the main() method:
public static void main(String args[])
{
}
For example:
public class Student //class definition
{
public static void main(String args[])
{
//statements
}
}
Chapter
Tokens
Java Tokens
Keyword:
Keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program.
Since keywords are referred names for a compiler, they can’t be used as variable names
because by doing so, we are trying to assign a new meaning to the keyword which is not
allowed.
Java language supports following keywords:
Identifiers
naming of variables, functions , arrays , classes , objects , methods , packages and interfaces
Ex: Length, name, marks,
Literals
Any constant value which can be assigned to the variable is called
literal/constant.
✓Integer
✓Floating point
✓Char
✓String
✓boolean
Integer Literals
• For Integral data types (byte, short, int, long), we can specify literals in 4
ways:-
• Decimal literals (Base 10): In this form, the allowed digits are 0-9.
• Ex:Int x=101;
• Octal literals (Base 8): In this form, the allowed digits are 0-7.
• Ex:Int x=0146;
• Hexa-decimal literals (Base 16): In this form, the allowed digits are 0-9,
and characters are a-f
• Ex :Int x=0x3456
• Binary literals - Literals value should be prefixed with 0b or 0B.
• Ex : int x=0b101101
Floating point Literal
For Floating-point data types, we can specify literals in only decimal form, and we cant
specify in octal and Hexadecimal forms.
double d=234.56;

Char literals
Single quote
• For char data types, we can specify literals in 4 ways:
• Single quote: We can specify literal to a char data type as a single character within the
single quote.
Ex: char ch=‘a’;
Char literal as Integral literal
✓ char literal as integral literal, which represents the Unicode value of the character, and
that integral literal can be specified either in Decimal, Octal, and Hexadecimal forms.
✓ allowed range is 0 to 65535.
Ex: char ch=062
Unicode Representation

We can specify char literals in Unicode representation ‘\uxxxx’


char ch = '\u0061';// Here /u0061 represent a

Escape sequence
Ex: char ch=‘\n’;
String Literals
Any sequence of characters within double quotes is treated as String
literals.
Ex: String s=“Hello”

Boolean literals
Only two values are allowed for Boolean literals, i.e., true and false.
Ex : Boolean b=true;
It is a symbol that takes one or
Operators more arguments and operates on
them to produce the result.

9. Boolean operators & , ! , !


Separators
White space
The most commonly used whitespace characters are \n, \t, \r and space.
Java Statements
Programming Style
• Free form – no indentation
Chapter
Naming Conventions & Data Types
Naming Conventions in Java
Naming conventions specify the rules to be followed by a Java programmer
while writing the names of packages, classes, methods, etc.
• package represents a sub directory that contains a group of classes and
interfaces. Names of packages in Java are written in small letters as:
java.awt;
java.io;

• Class is a model for creating objects.


✓ A class specifies the properties and actions of objects.
✓ An interface is also similar to a class.
✓ Each word of class names and interface names start with a capital letter as
✓ String
✓ DataInputStream
• A class and an interface contain methods and variables. The first word of a method name is
small letters; then from second word onwards, each new word starts with a capital letter
shown here:
Println()
readLine()
getNumberInstance

• The naming convention for variables names is same as that for methods
age
empName
employee Net sal

• Constants represent fixed values that cannot be altered. For example, PI is a constant who
value is 22/7 or 3.14159, which is fixed. Such constants should be written by using all
capital letters as shown here:
PI
MAX VALUE
Font.BOLD
Keywords should be written in small letters
Public
Void
Static
Integer Data Types

Ex;
public class Main{ public static void main(String[] args)
{
byte a=120;
System.out.println(a);
byte b=-128;
System.out.println(b);
byte c=127;
System.out.println(c);
byte d=128; //error //
System.out.println(d);
}}
Float Data Types
Char Data Types
String Data Types
Boolean Data Types

The eight primitives defined in Java are int, byte, short, long, float, double, Boolean,
and char
Default values of data types in Java
Scope , Visibility , Lifetime
• Scope is defined as the availability of a variable inside a program, scope is basically the
region of code in which a variable is available to use.
• Visibility of a variable is defined as if a variable is accessible or not inside a particular
region of code or the whole program.
• Lifetime of a variable is the time for which the variable is taking up a valid space in
the system's memory, it is of three types:
• static lifetime,
• automatic lifetime and
• dynamic lifetime.
✓ Static lifetime - Objects/Variables having a static lifetime will remain in the memory
until the execution of the program finishes.
Static int count =0 ;
✓ Automatic Lifetime - Objects/Variables declared inside a block have an automatic
lifetime. Local variables (those defined within a function) have an automatic lifetime
by default
✓ Objects/Variables which are made during the run-time of a C program using
the Dynamic Memory Allocation concept using the malloc(), calloc() functions
in C or new operator in C++ are stored in the memory until they are explicitly removed
from the memory using the free() function in C or delete operator in C++ and these
variables are said to have a dynamic lifetime
Chapter
Operators
Operator
An operator iS a symbol that performs an operation. An operator acts on some variables, called
operands to get the desired result,

✓ If an operator acts on a single variable, it 1s called unary operator;


✓ if it acts on two variables, it is called binary operators
✓ if it acts on three variables, then it is called ternary operator
Arithmetic Operators
Addition operator (+) is also used to join two strings, as shown n the following Code snin
String sl =“wel";
String s2= “come"
String s3= sl+s2; //
here, +is joining sl and s2
Now, we get welCome in s3.
In this case, + is called String concatenation operator.
Unary Operators
• As the name indicates, unary operators act on only one operand.
• There are 3 kinds o operators:
• Unary minus operator (-)
• Increment operator (++)
• Decrement operator ( --)
Unary Minus Operator (-)
• This operator is used to negate a given value. Negation means converting a negative value to
positive and vice versa, for example:
Increment Operator (++)
• This operator increases the value of a variable by 1, for example:
• Writing ++ before a variable is called pre incrementation and writing ++ after a
variable is called post incrementation.
• In pre incrementation, incrementation is done first and any other operation is
done next.
• In post incrementation, all the other operations are done first and
incrementation is done only at the end.
Decrement Operator (--)
• This operator is used to decrement the value of a variable by 1.
• Writing-- before a variable is called pre-decrementation and writing --
after a variable is called post-decrementation
Assignment Operator (=)
• This operator is used to store some value into a variable. It is used in 3
ways
• It is used to store a value into a variable, for It example
int x= 5;
• is used to store the value of a variable into another variable
int x=y;
• Store the value of an expression to a variable
int x= x+y+4;
Compact Notation
While using assignment operator (-), sometimes we may have to use same
variable at both the sides of the operator
Relational Operator
These operators are used for the purpose of comparing
Logical Operator
• Logical operators are used to construct combination of several compound
conditions.
• A Compound condition simple conditions. Logical operators are of three & and
types:

• ‘Logical AND’ Operator(&&)


• 'Logical OR' Operator(||)
• 'Logical NOT' Operator(!)
Boolean Operator
• These operators act on boolean variables and produce boolean type result.
• The following 3 boolean operators:
✓ & boolean and operator
✓ | boolean or operator
✓ ! boolean not operator

Boolean & operator returns true if both the variables are true.
Boolean | operator returns true one of the variables is true,
Boolean ! operator converts true to false and vice versa.
Bitwise Complement Operator (~)

• Change 1s to 0s and 0s to 1s
Ex: if x=10 then ~x = 0000 1010
Bitwise and Operator ( &)
• This operator performs and operation on the individual bits of the
numbers.
• The symbol for operator is &, which is called ampersand
Bitwise or Operator (|)
• This operator performs or operation on the bits of the numbers.
• The symbol is |, which is called pipe symbol.
Bitwise xor Operator (^)
• This operator performs exclusive or (xor) operation on the bits of the
numbers.
• The symbol is , which is called cap, carat, or circumflex symbol.
Bitwise Left Shift Operator (<<)
• shifts the bits of the number towards left a specified number of
positions.
• The symbol or this operator is << read as double less than, If we write
x<<n the meaning is to shift the bits towards left n positions.
Shifting the value of z towards left 2 positions will make the leftmost 2 bits
to be lost.
The value of x is 10 0000 1010. Now x<<2 will be 0010 1000=40 (in
decimal)
Bitwise Right Shift Operator (>>)
• This operator shifts the bits of the number towards
right a specified number of positions.
• The symbol for this operator is >>, read as double
greater than.
• If we write x>>n, the meaning is to shift he bits of x
towards right by n positions
• Shifting the value of x towards right 2 positions will
make the rightmost 2 bits to be lost. x value is 0000
1010.
• Now x>>2 will be: 0000 0010 = 2 (in decimal)
Bitwise Zero Fill Right Shift Operator (>>>)
• >>> - Triple greater than

The unsigned right shift operator (>>>) (zero-fill right shift) shifts the first operand the
specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits
are shifted in from the left. The sign bit becomes 0, so the result is always non-negative.
X=10, y=-10
X<<2

40
X>>2

2
X>>>2

2
Y<<2

Take 2s
complement

-40
Y>>2

Take 2s
complement

-3
Y>>>2

It is +ve number ,
hence do not
take 2s
complement

1073741821
Ternary / Conditional Operator(?:) )
• Acts on 3 variables
• value=expression1? expression2: expression3;
• Expression1 is evaluated ,
• if it is true then expression 2 is evaluated and stored in the variable value.
• if it is false then expression 3 is evaluated and stored in the variable value.
• Short form of if else
If expression1
Value=expression 2;
Else
Value= expression 3;
Member Operator (.)
Member operator is also called dot operator since its symbol is a. (dot or period).
This operator about member of a package or a class. It is used in three ways:

We know a package contains classes. We can use . operator to refer to the class of a packae
Syntax:
packagename.classname

We know that each class contains variables or methods. To refer to the variables of a class,
can use this operator
Using dot operator, we can refer to the method of a class.
instanceof Operator
✓ This operator is used to test if an object belongs to a class or not. Note that the
word instance means object.
✓ This operator can also be used to check if an object belongs to an interface or
not.
1)
int a =5 , b= 10 , c = -6;
boolean x= a>b && a<c ;
System.out.println(x);

Ans: false

2)
int a =5 , b= 10 , c = -6;
System.out.println(a==c || b> a);

Ans : true

3)
int a =5 , b= 10 , c = -6;
System.out.println(b>15 && c<0 || a>0);

Ans : true
4)

Ans : 64

5)

Ans : 17
6)
int i= 3;
System.out.println(i++ + i++);

Ans : 7

7)
Int i=3 ;
System.out.println(++i + ++i);

Ans: 9
Control Statements
The two most commonly used statements in any programming language are
as follows:
Sequential statements:
These are the statements which are executed one by one.
Control statements:
These are the statements that are executed randomly and repeatedly.

Following are the control statements in Java ;


✓ if .else statement
✓ do.while loop
✓ while loop
✓ for loop
✓ for-each loop
✓ Switch statement
✓ break statement
✓ continue statement
✓ Return statement
If –else
• This statement is used to perform a task depending on whether a given condition
is true or Here, task represents a single statement or a group of statements.
• Here, the condition is written inside the small braces ().
• The statements written inside the s brackets represent optional part of the
statement.
• It means that the part within [] omitted, if not required.
• This is the convention followed in all control statements.
• By observing the syntax, we can understand that if the condition specified after if
is true statements will be executed.
• If the condition is false, then statements2 will be exec statements and
statements2 represent either a single statement or more than one statement
• more than one statement is used, then they should be enclosed in angular
brackets
Do While loop
• This loop is used when there is a need to repeatedly execute a group of statements as long as a
condition is true.
• If the condition is false, the repetition will be stopped and the flow of execution comes out of do
While loop.
While loop
while (condition){
//code to be executed
Increment / decrement statement
}
Java For Loop
Java Simple for Loop
• A simple for loop is the same as C/C++. We can initialize the variable,
check condition and increment/decrement value. It consists of four
parts:
• Initialization: It is the initial condition which is executed once when the
loop starts. Here, we can initialize the variable, or we can use an already
initialized variable. It is an optional condition.
• Condition: It is the second condition which is executed each time to test
the condition of the loop. It continues execution until the condition is
false. It must return boolean value either true or false. It is an optional
condition.
• Increment/Decrement: It increments or decrements the variable value.
It is an optional condition.
• Statement: The statement of the loop is executed each time until the
second condition is false.
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Java Nested for Loop
• If we have a for loop inside the another loop, it is known as nested for loop. The
inner loop executes completely whenever outer loop executes.

public class NestedForExample {


public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
Java for-each Loop
• The for-each loop is used to traverse array or collection in Java. It is easier to use than
simple for loop because we don't need to increment value and use subscript notation.
• It works on the basis of elements and not the index. It returns element one by one in the
defined variable.
Syntax :
for(data_type variable : array_name){
//code to be executed
}

//Java For-each loop example which prints the


//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Switch statement
• Java Switch Statement
• The Java switch statement executes one statement from multiple conditions. It is like if-else-if
• ladder statement.
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables
• .
• The case values must be unique. In case of duplicate value, it renders compile-time error.
• The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums
• and string.
• Each case statement can have a break statement which is optional. When control reaches to
the break statement
• , it jumps the control after the switch expression. If a break statement is not found, it executes
the next case.
• The case value can have a default label which is optional.
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
Break statement
• The break statement in Java programming language has the following
two usages −
• When the break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
• It can be used to terminate a case in the switch statement

Syntax
The syntax of a break is a single statement inside any loop −
break;
Continue statement
• The continue statement is used in loop control structure when you need
to jump to the next iteration of the loop immediately.
• It can be used with for loop or while loop.
• The Java continue statement is used to continue the loop. It continues
the current flow of the program and skips the remaining code at the
specified condition.
• In case of an inner loop, it continues the inner loop only.
Syntax:
• jump-statement;
• continue;

You might also like