KEMBAR78
UNIT - 1 Java Fundamentals, Basics of java | PPTX
Unit No 1: Java Fundamentals
Review of Object oriented concepts, Evolution of Java, Comparison of
Java with other programming languages, Java features, Java and
World Wide Web, Java Run Time Environment. JVM architecture.
Overview of Java Language, Simple Java Program, Java Program
Structure. Installing and Configuring Java. Java Tokens, Java
Statements, Constants, variables, data types. Declaration of variables,
Giving values to variables, Scope of variables, arrays, Symbolic
constants, Typecasting, Getting values of variables, Standard default
values, Operators, Expressions, Type conversion in expressions,
Operator precedence and associatively, Mathematical functions,
Control statements- Decision making & looping.
Review of Object oriented concepts
• Object-Oriented Programming or Java OOPs concept refers to
languages that use objects in programming, they use objects as a
primary source to implement what is to happen in the code. Objects
are seen by the viewer or user, performing tasks you assign.
• Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism, etc. in programming. The main
aim of OOPs is to bind together the data and the functions that
operate on them so that no other part of the code can access this
data except that function.
• Access Modifier: Defines the access type of the method i.e. from where it can be accessed in your
application. In Java, there are 4 types of access specifiers:
• public: Accessible in all classes in your application.
• protected: Accessible within the package in which it is defined and in its subclass(es) (including subclasses
declared outside the package).
• private: Accessible only within the class in which it is defined.
• default (declared/defined without using any modifier): Accessible within the same class and package within which
its class is defined.
• The return type: The data type of the value returned by the method or void if it does not return a
value.
• Method Name: The rules for field names apply to method names as well, but the convention is a little
different.
• Parameter list: Comma-separated list of the input parameters that are defined, preceded by their data
type, within the enclosed parentheses. If there are no parameters, you must use empty parentheses
().
• Exception list: The exceptions you expect the method to throw. You can specify these exception(s).
• Method body: It is the block of code, enclosed between braces, that you need to execute to perform
your intended operations.
• OOPS concepts are as follows:
• Class
• Object
• Method and method passing
• Pillars of OOPs
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Compile-time polymorphism
• Runtime polymorphism
• A class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. Using classes,
you can create multiple objects with the same behavior instead of writing their code
multiple times. This includes classes for objects occurring more than once in your code. In
general, class declarations can include these components in order:
• Modifiers: A class can be public or have default access (Refer to this for details).
• Class name: The class name should begin with the initial letter capitalized by convention.
• Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
• Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
• Body: The class body is surrounded by braces, { }.
• An object is a basic unit of Object-Oriented Programming that represents real-life
entities. A typical Java program creates many objects, which as you know, interact
by invoking methods. The objects are what perform your code, they are the part
of your code visible to the viewer/user. An object mainly consists of:
• State: It is represented by the attributes of an object. It also reflects the
properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
• Identity: It is a unique name given to an object that enables it to interact with
other objects.
• Method: A method is a collection of statements that perform some specific task
and return the result to the caller. A method can perform some specific task
without returning anything. Methods allow us to reuse the code without retyping
it, which is why they are considered time savers. In Java, every method must be
part of some class, which is different from languages like C, C++, and Python.
public class GFG {
static String Employee_name;
static float Employee_salary;
static void set(String n, float p) {
Employee_name = n;
Employee_salary = p;
}
static void get() {
System.out.println("Employee name is: " +Employee_name );
System.out.println("Employee CTC is: " + Employee_salary);
}
public static void main(String args[]) {
GFG.set("Rathod Avinash", 10000.0f);
GFG.get();
}
} O/P: Employee name is: Rathod Avinash Employee CTC is: 10000.
• Abstraction
• Data Abstraction is the property by virtue of which only the essential details
are displayed to the user. The trivial or non-essential units are not displayed
to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object, ignoring the irrelevant details. The
properties and behaviors of an object differentiate it from other objects of
similar type and also help in classifying/grouping the object.
• Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the car speed or applying brakes will
stop the car, but he does not know how on pressing the accelerator, the
speed is actually increasing. He does not know about the inner mechanism of
the car or the implementation of the accelerators, brakes etc. in the car. This
is what abstraction is.
• Encapsulation
• It is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together the code and the data it manipulates.
Another way to think about encapsulation is that it is a protective shield that
prevents the data from being accessed by the code outside this shield.
• Technically, in encapsulation, the variables or the data in a class is hidden
from any other class and can be accessed only through any member function
of the class in which they are declared.
• In encapsulation, the data in a class is hidden from other classes, which is
similar to what data-hiding does. So, the terms “encapsulation” and “data-
hiding” are used interchangeably.
• Encapsulation can be achieved by declaring all the variables in a class as
private and writing public methods in the class to set and get the values of
the variables.
• Inheritance
• Inheritance is an important pillar of OOP (Object Oriented Programming). It is
the mechanism in Java by which one class is allowed to inherit the features
(fields and methods) of another class. We are achieving inheritance by
using extends keyword. Inheritance is also known as “is-a” relationship.
• Let us discuss some frequently used important terminologies:
• Superclass: The class whose features are inherited is known as superclass (also
known as base or parent class).
• Subclass: The class that inherits the other class is known as subclass (also
known as derived or extended or child class). The subclass can add its own
fields and methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class. By
doing this, we are reusing the fields and methods of the existing class.
• Polymorphism
• It refers to the ability of object-oriented programming languages to
differentiate between entities with the same name efficiently. This is done by
Java with the help of the signature and declaration of these entities. The
ability to appear in many forms is called polymorphism.
Evolution of Java
• Developed by Sun Microsystems in 1995, Java is a highly popular, object-
oriented programming language. This platform independent programming
language is utilized for Android development, web development, artificial
intelligence, cloud applications, and much more.
• Java is an Object-Oriented programming language developed by James
Gosling in the early 1990s. The team initiated this project 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 reasons(For instance C++ required more memory). Gosling try hard to
alter and expand C++ , however before long surrendered that for making
another stage called Green. James Gosling and his team called their project
“Greentalk” and its file extension was .gt and later became to known as
“OAK”.
For more information visit to : https://www.javatpoint.com/history-of-java
• The name Oak was used by Gosling after an oak tree that remained outside
his office. Also, Oak is an image of solidarity and picked as a national tree of
numerous nations like the U.S.A., France, Germany, Romania, etc. But they
had to later rename it as “JAVA” as it was already a trademark by Oak
Technologies. “JAVA” Gosling and his team did a brainstorm session and after
the session, they came up with several names such as JAVA, DNA, SILK,
RUBY, etc. Java name was decided after much discussion since it was so
unique.
• The name Java originates from a sort of espresso bean, Java. Gosling came
up with this name while having a coffee near his office. Java was created on
the principles like Robust, Portable, Platform Independent, High
Performance, Multithread, etc. and was called one of the Ten Best Products
of 1995 by the TIME MAGAZINE. Currently, Java is used in internet
programming, mobile devices, games, e-business solutions, etc.
Comparison of Java with other programming
languages
• Procedural Programming can be defined as a programming model which is
derived from structured programming, based upon the concept of calling
procedure. Procedures, also known as routines, subroutines or functions,
simply consist of a series of computational steps to be carried out. During a
program’s execution, any given procedure might be called at any point,
including by other procedures or itself.
• Object-oriented programming can be defined as a programming model which
is based upon the concept of objects. Objects contain data in the form of
attributes and code in the form of methods. In object-oriented programming,
computer programs are designed using the concept of objects that interact
with the real world. Object-oriented programming languages are various but
the most popular ones are class-based.
Java features
For more information visit to : https://www.javatpoint.com/features-of-java
• Simple
• Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java
language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.
• Object-oriented
• Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our
software as a combination of different types of objects that incorporate both data and behavior.
• Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing
some rules.
• Basic concepts of OOPs are:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Platform Independent
• Java is platform independent because it is different from other languages like C,
C++, etc. which are compiled into platform specific machines while Java is a write
once, run anywhere language. A platform is the hardware or software
environment in which a program runs.
• There are two types of platforms software-based and hardware-based. Java
provides a software-based platform.
Secured
• Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
• Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It
adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
• Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.
Robust
• The English meaning of Robust is strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these points make Java robust.
Architecture-neutral
• Java is architecture neutral because there are no implementation dependent features, for example, the size
of primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
• Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
High-performance
• Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code.
Distributed
• Java is distributed because it facilitates users to create distributed applications in Java. This feature of
Java makes us able to access files by calling the methods from any machine on the internet.
Multi-threaded
• A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it
doesn't occupy memory for each thread. It shares a common memory area. Threads are important for
multi-media, Web applications, etc.
Dynamic
• Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.
• Java supports dynamic compilation and automatic memory management (garbage collection).
Java and World Wide Web
• World Wide Web is an open-ended information retrieval system designed to be used in
the Internet’s distributed environment. This system contains what are known as
Web Pages that provides both information and controls. Unlike a menu – driven system
where we are guided through a particular direction using a decision tree structure, the
Web system is open-ended and we can navigate to a new document in any direction.
This is made possible with the help of a language called
Hypertext Markup Language (HTML). Web pages contain HTML tags that enable us to
find, retrieve, manipulate, and display documents worldwide.
• Java was meant to be used in distributed environments such as Internet. Since, both
the Web and Java share the same philosophy, Java could be easily incorporated into
the Web system. Before Java, the World Wide Web was limited to the display of still
images and texts. However, the incorporation of Java into the Web page has made it
capable of supporting animation, graphics, games, and a wide range of special effects.
With the support of Web, we can run Java program on someone else’s computer
access from the Internet.
• Java communicates with a Web page through a special tag called <APPLET>.
• The user sends a request for an HTML
document to the remote computer’s
Web server. The Web server is a
program that accepts a request,
processes the request, and sends the
request document.
• The HTML document is returned to the
user’s browser. The document contains
the APPLET tag, which identifies the
applet.
• The corresponding applet byte code is
transferred to the user’s computer. This
bytecode had been previously created
by the Java compiler using
Java source code file for that applet.
• The Java enabled browser on the user’s
computer interprets the byte codes
and provides output.
• The user may have further interaction
with the applet but with no further
downloading from the provider’s Web
server. This is because the bytecode
contains all the information necessary
to interpret the applet.
Java Run Time Environment
• Java Runtime Environment (JRE) is an open-access software distribution that has a Java
class library, specific tools, and a separate JVM. In Java, JRE is one of the interrelated
components in the Java Development Kit (JDK). It is the most common environment
available on devices for running Java programs. Java source code is compiled and
converted to Java bytecode. If you want to run this bytecode on any platform, you need
JRE. The JRE loads classes, check memory access and get system resources. JRE acts as
a software layer on top of the operating system.
• Components of Java JRE
• Integration libraries include Java Database Connectivity (JDBC)
• Java Naming, Interface Definition Language (IDL)
• Directory Interface (JNDI)
• Remote Method Invocation Over Internet Inter-Orb Protocol
• Remote Method Invocation (RMI)
• Scripting
• Java Virtual Machine (JVM) consists of Java HotSpot
Client and Server Virtual Machine.
• User interface libraries include Swing, Java 2D, Abstract
Window Toolkit (AWT), Accessibility, Image I/O, Print
Service, Sound, drag, and Drop (DnD), and input
methods.
• Lang and util base libraries, which include lang and util,
zip, Collections, Concurrency Utilities, management,
Java Archive (JAR), instrument, reflection, versioning,
Preferences API, Ref Objects, Logging, and Regular
Expressions.
• Other base libraries, including Java Management
Extensions (JMX), Java Native Interface (JNI), Math,
Networking, international support, input/output (I/O),
Beans, Java Override Mechanism, Security,
Serialization, extension mechanism, and Java for XML
Processing (XML JAXP).
• Deployment technologies such as Java Web Start,
deployment, and Java plug-in.
• Working of JRE
• Java Development Kit (JDK) and Java Runtime Environment (JRE) both interact with
each other to create a sustainable runtime environment that enables Java-based
applications to run seamlessly on any operating system. The JRE runtime architecture
consists of the following elements as listed:
• ClassLoader
• ByteCode verifier
• Interpreter
• ClassLoader: Java ClassLoader dynamically loads all the classes necessary to run a Java
program. Because classes are only loaded into memory whenever they are needed,
the JRE uses ClassLoader will automate this process when needed. During the
initialization of the JVM, three classLoaders are loaded:
• Bootstrap class loader
• Extensions class loader
• System class loader
• Bytecode Verifier: The bytecode checker ensures the format and precision of Java code
before passing it to the interpreter. If the code violates system integrity or access rights, the
class is considered corrupt and will not load.
• Interpreter: After loading the byte code successfully, the Java interpreter creates an object
of the Java virtual machine that allows the Java program to run natively on the underlying
machine.
• JRE has an object of JVM with it, development tools, and library classes.
// Java class
class hello{
// Main driver method
public static void main(String[] args) {
// Print statement
System.out.println(“Hello World");
}
}
• O/p - Hello World
• Once you write this program, you have to save it with .java extension. Compile your
program. The output of the Java compiler is a byte-code which is platform independent.
After compiling, the compiler generates a .class file which has the bytecode. The bytecode is
platform independent and runs on any device having the JRE. From here, the work of JRE
begins. To run any Java program, you need JRE. The flow of the bytecode to run is as
diagram:
Difference between JVM, JRE, and JDK.
• JVM: JVM stands for Java Virtual Machine. JVM is used for running Java
bytecode.Java applications are called WORA (Write Once Run Anywhere).
This means a programmer can develop Java code on one system and can
expect it to run on any other Java-enabled system without any adjustment.
This is all possible because of JVM.
• JRE: JRE stands for Java Runtime Environment. JRE is made up of class
libraries.
• JDK: JDK stands for Java Development Kit. JDK contains the JRE with compiler,
interpreter, debugger, and other tools. It provides features to run as well as
develop Java Programs.
JVM architecture
• JVM (Java Virtual Machine)
is an abstract machine. It is
a specification that
provides runtime
environment in which java
bytecode can be executed.
• JVMs are available for
many hardware and
software platforms (i.e.
JVM is platform
dependent).
What is JVM
A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Oracle and other companies.
• Its implementation is known as JRE (Java Runtime Environment).
• Runtime Instance Whenever you write java command on the command prompt to run the java class, an
instance of JVM is created.
The JVM performs following operation:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
• JVM provides definitions for the:
• Memory area
• Class file format
• Register set
• Garbage-collected heap
• Fatal error reporting etc.
1) Classloader
Classloader 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 ClassLoader: 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 Standard Edition like java.lang package classes, java.net package classes,
java.util package classes, java.io package classes, java.sql package classes etc.
• 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. You can change the classpath using "-cp" or "-classpath"
switch. It is also known as Application classloader.
//Let's see an example to print the classloader name
public class ClassLoaderExample
{
public static void main(String[] args)
{
// Let's print the classloader name of current class.
//Application/System classloader will load this class
Class c=ClassLoaderExample.class;
System.out.println(c.getClassLoader());
//If we print the classloader name of String, it will print null because it is an
//in-
built class which is found in rt.jar, so it is loaded by Bootstrap classloader
System.out.println(String.class.getClassLoader());
}
}
O/p :
sun.misc.Launcher$AppClassLoader@4e0e2f2a
2) Class(Method) Area
It is memory block stores, class code, variable code ,runtime constant & Constructor of java.
(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.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
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
It contains:
A virtual processor
Interpreter: Read bytecode stream then execute the instructions.
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. Here, the
term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction
set of a specific CPU.
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.
The requirement for Java
Hello World Example
For executing any Java program, the
following software or application must
be properly installed.
1. Install the JDK if you don't
have installed it, download
the JDK and install it.
2. Set path of the jdk/bin
directory.
http://www.javatpoint.com/
how-to-set-path-in-java
3. Create the Java program
4. Compile and run the Java
program
Creating Hello World Example. Let's create the hello java program:
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Save the above file as Simple.java.
To compile:
javac Simple.java
To execute:
java Simple
Output:
Hello Java
• Compilation Flow:
• When we compile Java program using javac tool, the Java compiler converts
the source code into byte code.
Java Code
(Simple.java)
Byte Code
(Simple.class)
Compiler
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
• class keyword is used to declare a class in Java.
• public keyword is an access modifier that represents visibility. Here Public means it is
visible to all.
• static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to create an
object to invoke the static method. The main() method is executed by the JVM, so it
doesn't require creating an object to invoke the main() method. So, it saves memory.
• void is the return type of the method. It means it doesn't return any value.
• main represents the starting point of the program.
• String[] args or String args[] is used for command line argument.
• System.out.println() is used to print statement. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class.
Java Program Structure
• 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 Behaviors
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.
• Single-line Comment: It starts with a pair of forwarding slash (//). For example: //First Java
Program
• Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols. For example: /*It is an example of
• multiline comment*/
• Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:
• /**It is an example of documentation comment*/
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 javapvpit; //where javapvpit is the package name
package com. javapvpit; //where com is the root directory and javapvpit is the subdirectory
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. We use the 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. We use the 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. We can use interface in classes by using the
implements keyword. An interface can also be used with other interfaces by using the extends keyword.
• It is used for total abstraction. Java doesn’t support multiple inheritance in case of class, by using interface. Any
class extends only one class but any class can implement infinite no.of interfaces.
• For example:
interface car
{ void start(); void stop(); }
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we cannot create any Java
program. A Java program may perform 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 this section, we define variables and constants that are to be used later in the program. 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
In this section, we define the main() method. It is essential for all Java programs. Because the execution of all Java
programs starts from the main() method. In other words, 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[])
{ }
public class Student //class definition
{
public static void main(String args[])
{
//statements
} }
Methods and behavior
In this section, we define the functionality of the program by using the methods. The methods are the
set of instructions that we want to perform. These instructions execute at runtime and perform the
specified task. For example:
public class Demo //class definition
{
public static void main(String args[])
{
void display()
{
System.out.println("Welcome to javatpoint");
}
//statements
}
}
/*Program name: Palindrome*/
Java Tokens
• In Java, the program contains classes and methods. Further, the methods contain
the expressions and statements required to perform a specific operation. These
statements and expressions are made up of tokens. In other words, we can say
that the expression and statement is a set of tokens. The tokens are the small
building blocks of a Java program that are meaningful to the Java compiler.
Further, these two components contain variables, constants, and operators.
What is token in Java?
• The Java compiler breaks the line of code into text (words) is called Java tokens.
These are the smallest element of the Java program. The Java compiler identified
these words as tokens. These tokens are separated by the delimiters. It is useful
for compilers to detect errors. Remember that the delimiters are not part of the
Java tokens.
• token <= identifier | keyword | separator | operator | literal | comment
For example, consider the following code.
public class Demo
{
public static void main(String args[])
{
System.out.println("javatpoint");
}
} In the above code snippet, public, class, Demo, {,
static, void, main, (, String, args, [, ], ), System, .,
out, println, javatpoint, etc. are the Java tokens.
The Java compiler translates these tokens into
Java bytecode. Further, these bytecodes are
executed inside the interpreted Java
environment.
Types of
Tokens
• Java token
includes the
following:
• Keywords
• Identifiers
• Literals
• Operators
• Separators
• Comments
Keywords: These are the pre-defined reserved words of any
programming language. Each keyword has a special meaning. It is
always written in lower case. Java provides the following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final
16. finally 17. float 18. for 19. if 20. implements
21. import 22. instanceof 23. int 24. interface 25. long
26. native 27. new 28. package 29. private 30. protected
31. public 32. return 33. short 34. static 35. super
36. switch 37. synchronized 38. this 39. thro 40. throws
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
• Identifier: Identifiers are used to name a variable,
constant, function, class, and array. It usually
defined by the user. It uses letters, underscores, or
a dollar sign as the first character. The label is also
known as a special kind of identifier that is used in
the goto statement. Remember that the identifier
name must be different from the reserved
keywords. There are some rules to declare
identifiers are:
• The first letter of an identifier must be a letter,
underscore or a dollar sign. It cannot start with
digits but may contain digits.
• The whitespace cannot be included in the
identifier.
Some valid identifiers
are:
PhoneNumber
PRICE
radius
a
a1
_phonenumber
$circumference
jagged_array
12radius //invalid
•Literals: In programming literal is a notation that represents
a fixed value (constant) in the source code. It can be
categorized as an integer literal, string literal, Boolean
literal, etc. It is defined by the programmer. Once it has
been defined cannot be changed. Java provides five types of
literals are as follows:
•Integer
•Floating Point
•Character
•String
•Boolean
• Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators that can be
classified according to the functionality they provide. There are eight types of
operators in Java, are as follows:
• Arithmetic Operators
• Assignment Operators
• Relational Operators
• Unary Operators
• Logical Operators
• Ternary Operators
• Bitwise Operators
• Shift Operators
Operator Symbols
Arithmetic + , - , / , * , %
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Relational ==, != , < , >, <= , >=
Logical && , ||
Ternary (Condition) ? (Statement1) :
(Statement2);
Bitwise & , | , ^ , ~
• Separators: The separators in Java is also known as punctuators. There are nine separators in
Java, are as follows:
• separator <= ; | , | . | ( | ) | { | } | [ | ]
• Note that the first three separators (; , and .) are tokens that separate other tokens, and the
last six (3 pairs of braces) separators are also known as delimiters. For example, Math.pow(9,
3); contains nine tokens.
• Square Brackets []: It is used to define array elements. A pair of square brackets represents
the single-dimensional array, two pairs of square brackets represent the two-dimensional
array.
• Parentheses (): It is used to call the functions and parsing the parameters.
• Curly Braces {}: The curly braces denote the starting and ending of a code block.
• Comma (,): It is used to separate two values, statements, and parameters.
• Assignment Operator (=): It is used to assign a variable and constant.
• Semicolon (;): It is the symbol that can be found at end of the statements. It separates the
two statements.
• Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.
•Comments: Comments allow us to specify information
about the program inside our Java code. Java compiler
recognizes these comments as tokens but excludes it form
further processing. The Java compiler treats comments as
whitespaces. Java provides the following two types of
comments:
•Line Oriented: It begins with a pair of forwarding slashes
(//).
•Block-Oriented: It begins with /* and continues until it
founds */.
Java Statements
• Statements are roughly equivalent to sentences in natural languages.
In general, statements are just like English sentences that make valid
sense.
• What is statement in Java?
• In Java, a statement is an executable instruction that tells the compiler
what to perform. It forms a complete command to be executed and
can include one or more expressions. A sentence forms a complete
idea that can include one or more clauses.
Types of Statements
• Expression Statements
• Declaration Statements
• Control Statements
Expression Statements
• Expression is an essential building block of any Java program. Generally, it is used to
generate a new value. Sometimes, we can also assign a value to a variable. In Java,
expression is the combination of values, variables, operators, and method calls.
• There are three types of expressions in Java:
• Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2. Note
that the expression enclosed in the parentheses will be evaluate first, after that rest
of the expression.
• Expressions that assign a value. For example, number = 90, pi = 3.14.
• Expression that neither produces any result nor assigns a value. For
example, increment or decrement a value by using increment or decrement
operator respectively, method invocation, etc. These expressions modify the value
of a variable or state (memory) of a program. For example, count++, int sum = a +
b; The expression changes only the value of the variable sum. The value of
variables a and b do not change, so it is also a side effect.
Declaration Statements
In declaration statements, we declare variables and constants by specifying their data type
and name. A variable holds a value that is going to use in the Java program. For example:
• int quantity;
• boolean flag;
• String message;
Also, we can initialize a value to a variable. For example:
• int quantity = 20;
• boolean flag = false;
• String message = "Hello";
Java also allows us to declare multiple variables in a single declaration statement. Note
that all the variables must be of the same data type.
• int quantity, batch_number, lot_number;
• boolean flag = false, isContains = true;
• String message = "Hello", how are you;
Control Statement
• Control statements decide the flow (order or sequence of execution of
statements) of a Java program. In Java, statements are parsed from top to
bottom. Therefore, using the control flow statements can interrupt a particular
section of a program based on a certain condition.
• Conditional or Selection Statements
• if Statement
• if-else statement
• if-else-if statement
• switch statement
• Loop or Iterative Statements
• for Loop
• while Loop
• do-while Loop
• for-each Loop
• Flow Control or Jump Statements
• return
• continue
• break
Example of Statement
//declaration statement
int number;
//expression statement
number = 412;
//control flow statement
if (number > 10 )
{
//expression statement
System.out.println(number + " is greater
than 100");
}
Java Constants
As the name suggests, a constant is an entity in programming that is immutable. In other words,
the value that cannot be changed.
What is constant?
• Constant is a value that cannot be changed after assigning it. Java does not directly support the
constants. There is an alternative way to define the constants in Java by using the non-access
modifiers static and final.
How to declare constant in Java?
• In Java, to declare any variable as constant, we use static and final modifiers. It is also known
as non-access modifiers. According to the Java naming convention the identifier name must be
in capital letters.
Static and Final Modifiers
• The purpose to use the static modifier is to manage the memory.
• It also allows the variable to be available without loading any instance of the class in which it is
defined.
• The final modifier represents that the value of the variable cannot be changed. It also makes the
primitive data type immutable or unchangeable.
The syntax to declare a constant is as follows:
•static final datatype identifier_name=value;
•For example, price is a variable that we want to make constant.
•static final double PRICE=432.78;
•Where static and final are the non-access modifiers. The
double is the data type and PRICE is the identifier name in
which the value 432.78 is assigned.
•In the above statement, the static modifier causes the variable
to be available without an instance of its defining class being
loaded and the final modifier makes the variable fixed.
Why we use both static and final modifiers to declare a constant?
• If we declare a variable as static, all the objects of the class (in which
constant is defined) will be able to access the variable and can be
changed its value. To overcome this problem, we use
the final modifier with a static modifier.
• When the variable defined as final, the multiple instances of the same
constant value will be created for every different object which is not
desirable.
• When we use static and final modifiers together, the variable remains
static and can be initialized once. Therefore, to declare a variable as
constant, we use both static and final modifiers. It shares a common
memory location for all objects of its containing class.
Why we use constants?
• The use of constants in programming makes the program easy and
understandable which can be easily understood by others. It also
affects the performance because a constant variable is cached by both
JVM and the application.
Points to Remember:
• Write the identifier name in capital letters that we want to declare as
constant. For example, MAX=12.
• If we use the private access-specifier before the constant name, the
value of the constant cannot be changed in that particular class.
• If we use the public access-specifier before the constant name, the
value of the constant can be changed in the program.
Enum : It is a special data types that consists of a set of pre-
defined named values separated by commas
•Using Enumeration (Enum) as Constant
•It is the same as the final variables.
•It is a list of constants.
•Java provides the enum keyword to define the enumeration.
•It defines a class type by making enumeration in the class that
may contain instance variables, methods, and constructors.
Example of Enumeration(Do practical)
public class EnumExample
{
//defining the enum
public enum Color {Red, Green, Blue, Purple, Black, White, Pink, Gray}
public static void main(String[] args)
{
//traversing the enum
for (Color c : Color.values())
System.out.println(c);
}
}
Output:
Variables- Declaration , Giving values & Scope of
variables
• Variable Declaration is a statement that provides the variable name and its type, allowing the
program to allocate memory for storing values.
Importance of Variable Declaration:
• Memory Allocation: When we declare a variable, we tell the computer to reserve some space
in memory. This space is where the data associated with the variable will be stored.
• Data Type Specification: Variable declaration also involves specifying the type of data the
variable will hold (like a number, text, etc.). This helps the computer know how much memory
to allocate for the variable.
• Code Readability and Maintenance: Declaring variables makes our code easier to read and
maintain. It gives meaningful names to data, which makes the code self-explanatory.
• Avoiding Errors: If we try to use a variable that hasn’t been declared, the computer won’t
know what we’re referring to, and this will lead to an error.
• Scope Definition: Variable declaration defines the scope of the variable, i.e., the part of the
code where the variable can be accessed.
• Variable Declaration in Java:
// Declaring an integer variable named
'a'
int a;
// Declaring a float variable named 'b'
float b;
// Declaring a character variable
named 'c'
char c;
How to Initialize Variables in Java?
It can be perceived with the help of 3
components that are as follows:
datatype: Type of data that can be
stored in this variable.
variable_name: Name given to the
variable.
value: It is the initial value stored in
the variable.
Types of Variables in Java
Local Variables
Instance Variables
Static Variables
• 1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
The Local variable is created at the time of declaration and destroyed after exiting from the block or when the call
returns from the function.
The scope of these variables exists only within the block in which the variables are declared, i.e., we can access
these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined scope.
// Local Variables - Java Program to implement
import java.io.*;
class PVP {
public static void main(String[] args)
{
int var = 10; // Declared a Local Variable
System.out.println("Local Variable: " + var); // This variable is local to this main method only
}
}
2. Instance Variables
• Instance variables are non-static variables and are declared in a class outside of
any method, constructor, or block.
• As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
• Unlike local variables, we may use access specifiers for instance variables. If we
do not specify any access specifier, then the default access specifier will be used.
• Initialization of an instance variable is not mandatory. Its default value is
dependent on the data type of variable. For String it
is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null,
etc.
• Instance variables can be accessed only by creating objects.
• We initialize instance variables using constructors while creating an object.
• The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes.
• The static can be:
• Variable (also known as a class variable)
• Method (also known as a class method)
• Block
• Nested class
Java static variable
• If you declare any variable as static, it is known as a static variable.
• The static variable gets memory only once in the class area at the time of class
loading.
• It makes your program memory efficient (i.e., it saves memory).
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the common
property of all objects. If we make it static, this field will get the memory only once.
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
3. Static Variables
• Static variables are also known as class variables.
• These variables are declared similarly to instance variables. The difference is that static variables are
declared using the static keyword within a class outside of any method, constructor, or block.
• Unlike instance variables, we can only have one copy of a static variable per class, irrespective of how
many objects we create.
• Static variables are created at the start of program execution and destroyed automatically when
execution ends.
• Initialization of a static variable is not mandatory. Its default value is dependent on the data type of
variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it
is null, etc.
• If we access a static variable like an instance variable (through an object), the compiler will show a
warning message, which won’t halt the program. The compiler will replace the object name with the
class name automatically.
• If we access a static variable without the class name, the compiler will automatically append the class
name. But for accessing the static variable of a different class, we must mention the class name as 2
different classes might have a static variable with the same name.
• Static variables cannot be declared locally inside an instance method.
• Static blocks can be used to initialize static variables.
• Differences Between the Instance Variables and the Static Variables
• Each object will have its own copy of an instance variable, whereas we can only
have one copy of a static variable per class, irrespective of how many objects we
create. Thus, static variables are good for memory management.
• Changes made in an instance variable using one object will not be reflected in
other objects as each object has its own copy of the instance variable. In the case
of a static variable, changes will be reflected in other objects as static variables
are common to all objects of a class.
• We can access instance variables through object references, and static variables
can be accessed directly using the class name.
• Instance variables are created when an object is created with the use of the
keyword ‘new’ and destroyed when the object is destroyed. Static variables are
created when the program starts and destroyed when the program stops.
Array
• Normally, an array is a collection of similar type of elements which has
continuous memory location.
• Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array.
• Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
• Unlike C/C++, we can get the length of the array using the length member. In
C/C++, we need to use the sizeof operator.
• We can store primitive values or objects in an array in Java. Like C/C++, we can
also create single dimentional or multidimentional arrays in Java.
Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
• Random access: We can get any data located at an index position.
Disadvantages
• Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
Java which grows automatically.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Symbolic constant
• In Java, a symbolic constant is a named constant value defined once and used
throughout a program. Symbolic constants are declared using the final keyword.
• Which indicates that the value cannot be changed once it is initialized.
• The naming convention for symbolic constants is to use all capital letters with
underscores separating words.
Syntax of Symbolic Constants
• final data_type CONSTANT_NAME = value;
Initializing a symbolic constant:
• final double PI = 3.14159;
// Java Program to print an Array (Do practical)
import java.io.*;
public class Example {
public static final int MAX_SIZE = 10;
public static void main(String[] args)
{
int[] array = new int[MAX_SIZE];
for (int i = 0; i < MAX_SIZE; i++) {
array[i] = i * 2;
}
System.out.print("Array: ");
for (int i = 0; i < MAX_SIZE; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
Array: 0 2 4 6 8 10 12 14 16 18
Type Casting in Java
• In Java, type casting is a method or process that converts a data type
into another data type in both ways manually and automatically. The
automatic conversion is done by the compiler and manual conversion
performed by the programmer.
Type casting
• Convert a value from one data type to another data type is known as type casting.
Types of Type Casting
There are two types of type casting:
• Widening Type Casting
• Narrowing Type Casting
• Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known as implicit
conversion or casting down. It is done automatically. It is safe because there is no chance to lose data. It takes
place when:
• Both data types must be compatible with each other.
• The target type must be larger than the source type.
• Narrowing Type Casting
• Converting a higher data type into a lower one is called narrowing type casting. It is also known as explicit
conversion or casting up. It is done manually by the programmer. If we do not perform casting then the
compiler reports a compile-time error.
public class WideningTypeCastingExample
{ public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
public class NarrowingTypeCastingExample
{ public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
Default Values Assigned to Primitive Data
Types in Java
• In Java, when a variable is declared but not initialized, it is assigned a default value based on its data type. The default values for
the primitive data types in Java are as follows:
• byte: 0
• short: 0
• int: 0
• long: 0L
• float: 0.0f
• double: 0.0d
• char: ‘u0000’ (null character)
• boolean: false
• It is important to note that these default values are only assigned if the variable is not explicitly initialized with a value. If a variable
is initialized with a value, that value will be used instead of the default.
• Primitive data types are built-in data types in java and can be used directly without using any new keyword. As we know primitive
data types are treated differently by java cause of which the wrapper class concept also comes into play. But here we will be
entirely focussing on data types. So, in java, there are 8 primitive data types as shown in the table below with their corresponding
sizes.
Data Type Size
Byte 1 byte
Short 2 bytes
Int 4 bytes
Long 8 bytes
Float 4 bytes
Double 8 bytes
Boolean 1 bit
Char 1 byte
Now, here default values are values assigned by
the compiler to the variables which are declared
but not initialized or given a value. They are
different according to the return type of data type
which is shown below where default values
assigned to variables of different primitive data
types are given in the table. However, relying on
such default values is not considered a good
programming style.
Operator
Precedenc
e in Java
(Highest
to Lowest)
Category Operators Associativity
Postfix ++ - - Left to right
Unary + - ! ~ ++ - - Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Operator Precedence Vs. Operator Associativity
• The operator's precedence refers to the order in which operators are
evaluated within an expression whereas associativity refers to the
order in which the consecutive operators within the same group are
carried out.
Mathematical functions
• Java Math class provides several methods to work on math calculations like
min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
• Unlike some of the StrictMath class numeric methods, all implementations of the
equivalent function of Math class can't define to return the bit-for-bit same
results. This relaxation permits implementation with better-performance where
strict reproducibility is not required.
• If the size is int or long and the results overflow the range of value, the methods
addExact(), subtractExact(), multiplyExact(), and toIntExact() throw
an ArithmeticException.
• For other arithmetic operations like increment, decrement, divide, absolute
value, and negation overflow occur only with a specific minimum or maximum
value. It should be checked against the maximum and minimum value as
appropriate.
Method Description
Math.abs() It will return the Absolute value of the given value.
Math.max() It returns the Largest of two values.
Math.min() It is used to return the Smallest of two values.
Math.round() It is used to round of the decimal numbers to the nearest value.
Math.sqrt() It is used to return the square root of a number.
Math.cbrt() It is used to return the cube root of a number.
Math.pow() It returns the value of first argument raised to the power to second argument.
Math.signum() It is used to find the sign of a given value.
Math.ceil() It is used to find the smallest integer value that is greater than or equal to the argument or
mathematical integer.
Math.copySign() It is used to find the Absolute value of first argument along with sign specified in second
argument.
Math.nextAfter() It is used to return the floating-point number adjacent to the first argument in the direction
of the second argument.
Math.nextUp() It returns the floating-point value adjacent to d in the direction of positive infinity.
Math.nextDown() It returns the floating-point value adjacent to d in the direction of negative infinity.
Math.floor() It is used to find the largest integer value which is less than or equal to the argument and is
equal to the mathematical integer of a double value.
Math.random() It returns a double value with a positive sign, greater than or equal to 0.0 and less
than 1.0.
Math.rint() It returns the double value that is closest to the given argument and equal to
mathematical integer.
Math.hypot() It returns sqrt(x2
+y2
) without intermediate overflow or underflow.
Math.ulp() It returns the size of an ulp of the argument.
Math.getExponent() It is used to return the unbiased exponent used in the representation of a value.
Math.IEEEremainder() It is used to calculate the remainder operation on two arguments as prescribed by the
IEEE 754 standard and returns value.
Math.addExact() It is used to return the sum of its arguments, throwing an exception if the result
overflows an int or long.
Math.subtractExact() It returns the difference of the arguments, throwing an exception if the result overflows
an int.
Math.multiplyExact() It is used to return the product of the arguments, throwing an exception if the result
overflows an int or long.
Math.incrementExact() It returns the argument incremented by one, throwing an exception if the result
overflows an int.
Math.decrementExact(
)
It is used to return the argument decremented by one, throwing an exception if the
result overflows an int or long.
Math.negateExact() It is used to return the negation of the argument, throwing an exception if the result
Logarithmic Math Methods
Method Description
Math.log() It returns the natural logarithm of a double value.
Math.log10() It is used to return the base 10 logarithm of a double value.
Math.log1p() It returns the natural logarithm of the sum of the argument
and 1.
Math.exp() It returns E raised to the power of a double value, where E is
Euler's number and it is approximately equal to 2.71828.
Math.expm1() It is used to calculate the power of E and subtract one from it.
Trigonometric Math Methods
Method Description
Math.sin() It is used to return the trigonometric Sine value of a Given double
value.
Math.cos() It is used to return the trigonometric Cosine value of a Given double
value.
Math.tan() It is used to return the trigonometric Tangent value of a Given double
value.
Math.asin() It is used to return the trigonometric Arc Sine value of a Given double
value
Math.acos() It is used to return the trigonometric Arc Cosine value of a Given
double value.
UNIT - 1  Java Fundamentals, Basics of java

UNIT - 1 Java Fundamentals, Basics of java

  • 1.
    Unit No 1:Java Fundamentals Review of Object oriented concepts, Evolution of Java, Comparison of Java with other programming languages, Java features, Java and World Wide Web, Java Run Time Environment. JVM architecture. Overview of Java Language, Simple Java Program, Java Program Structure. Installing and Configuring Java. Java Tokens, Java Statements, Constants, variables, data types. Declaration of variables, Giving values to variables, Scope of variables, arrays, Symbolic constants, Typecasting, Getting values of variables, Standard default values, Operators, Expressions, Type conversion in expressions, Operator precedence and associatively, Mathematical functions, Control statements- Decision making & looping.
  • 2.
    Review of Objectoriented concepts • Object-Oriented Programming or Java OOPs concept refers to languages that use objects in programming, they use objects as a primary source to implement what is to happen in the code. Objects are seen by the viewer or user, performing tasks you assign. • Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOPs is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.
  • 3.
    • Access Modifier:Defines the access type of the method i.e. from where it can be accessed in your application. In Java, there are 4 types of access specifiers: • public: Accessible in all classes in your application. • protected: Accessible within the package in which it is defined and in its subclass(es) (including subclasses declared outside the package). • private: Accessible only within the class in which it is defined. • default (declared/defined without using any modifier): Accessible within the same class and package within which its class is defined. • The return type: The data type of the value returned by the method or void if it does not return a value. • Method Name: The rules for field names apply to method names as well, but the convention is a little different. • Parameter list: Comma-separated list of the input parameters that are defined, preceded by their data type, within the enclosed parentheses. If there are no parameters, you must use empty parentheses (). • Exception list: The exceptions you expect the method to throw. You can specify these exception(s). • Method body: It is the block of code, enclosed between braces, that you need to execute to perform your intended operations.
  • 4.
    • OOPS conceptsare as follows: • Class • Object • Method and method passing • Pillars of OOPs • Abstraction • Encapsulation • Inheritance • Polymorphism • Compile-time polymorphism • Runtime polymorphism
  • 5.
    • A classis a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. Using classes, you can create multiple objects with the same behavior instead of writing their code multiple times. This includes classes for objects occurring more than once in your code. In general, class declarations can include these components in order: • Modifiers: A class can be public or have default access (Refer to this for details). • Class name: The class name should begin with the initial letter capitalized by convention. • Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. • Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. • Body: The class body is surrounded by braces, { }.
  • 6.
    • An objectis a basic unit of Object-Oriented Programming that represents real-life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. The objects are what perform your code, they are the part of your code visible to the viewer/user. An object mainly consists of: • State: It is represented by the attributes of an object. It also reflects the properties of an object. • Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects. • Identity: It is a unique name given to an object that enables it to interact with other objects. • Method: A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping it, which is why they are considered time savers. In Java, every method must be part of some class, which is different from languages like C, C++, and Python.
  • 7.
    public class GFG{ static String Employee_name; static float Employee_salary; static void set(String n, float p) { Employee_name = n; Employee_salary = p; } static void get() { System.out.println("Employee name is: " +Employee_name ); System.out.println("Employee CTC is: " + Employee_salary); } public static void main(String args[]) { GFG.set("Rathod Avinash", 10000.0f); GFG.get(); } } O/P: Employee name is: Rathod Avinash Employee CTC is: 10000.
  • 8.
    • Abstraction • DataAbstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or non-essential units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components. Data Abstraction may also be defined as the process of identifying only the required characteristics of an object, ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the object. • Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the car speed or applying brakes will stop the car, but he does not know how on pressing the accelerator, the speed is actually increasing. He does not know about the inner mechanism of the car or the implementation of the accelerators, brakes etc. in the car. This is what abstraction is.
  • 9.
    • Encapsulation • Itis defined as the wrapping up of data under a single unit. It is the mechanism that binds together the code and the data it manipulates. Another way to think about encapsulation is that it is a protective shield that prevents the data from being accessed by the code outside this shield. • Technically, in encapsulation, the variables or the data in a class is hidden from any other class and can be accessed only through any member function of the class in which they are declared. • In encapsulation, the data in a class is hidden from other classes, which is similar to what data-hiding does. So, the terms “encapsulation” and “data- hiding” are used interchangeably. • Encapsulation can be achieved by declaring all the variables in a class as private and writing public methods in the class to set and get the values of the variables.
  • 10.
    • Inheritance • Inheritanceis an important pillar of OOP (Object Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another class. We are achieving inheritance by using extends keyword. Inheritance is also known as “is-a” relationship. • Let us discuss some frequently used important terminologies: • Superclass: The class whose features are inherited is known as superclass (also known as base or parent class). • Subclass: The class that inherits the other class is known as subclass (also known as derived or extended or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
  • 11.
    • Polymorphism • Itrefers to the ability of object-oriented programming languages to differentiate between entities with the same name efficiently. This is done by Java with the help of the signature and declaration of these entities. The ability to appear in many forms is called polymorphism.
  • 12.
    Evolution of Java •Developed by Sun Microsystems in 1995, Java is a highly popular, object- oriented programming language. This platform independent programming language is utilized for Android development, web development, artificial intelligence, cloud applications, and much more. • Java is an Object-Oriented programming language developed by James Gosling in the early 1990s. The team initiated this project 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 reasons(For instance C++ required more memory). Gosling try hard to alter and expand C++ , however before long surrendered that for making another stage called Green. James Gosling and his team called their project “Greentalk” and its file extension was .gt and later became to known as “OAK”. For more information visit to : https://www.javatpoint.com/history-of-java
  • 13.
    • The nameOak was used by Gosling after an oak tree that remained outside his office. Also, Oak is an image of solidarity and picked as a national tree of numerous nations like the U.S.A., France, Germany, Romania, etc. But they had to later rename it as “JAVA” as it was already a trademark by Oak Technologies. “JAVA” Gosling and his team did a brainstorm session and after the session, they came up with several names such as JAVA, DNA, SILK, RUBY, etc. Java name was decided after much discussion since it was so unique. • The name Java originates from a sort of espresso bean, Java. Gosling came up with this name while having a coffee near his office. Java was created on the principles like Robust, Portable, Platform Independent, High Performance, Multithread, etc. and was called one of the Ten Best Products of 1995 by the TIME MAGAZINE. Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
  • 14.
    Comparison of Javawith other programming languages • Procedural Programming can be defined as a programming model which is derived from structured programming, based upon the concept of calling procedure. Procedures, also known as routines, subroutines or functions, simply consist of a series of computational steps to be carried out. During a program’s execution, any given procedure might be called at any point, including by other procedures or itself. • Object-oriented programming can be defined as a programming model which is based upon the concept of objects. Objects contain data in the form of attributes and code in the form of methods. In object-oriented programming, computer programs are designed using the concept of objects that interact with the real world. Object-oriented programming languages are various but the most popular ones are class-based.
  • 15.
    Java features For moreinformation visit to : https://www.javatpoint.com/features-of-java
  • 16.
    • Simple • Javais very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because: • Java syntax is based on C++ (so easier for programmers to learn it after C++). • Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc. • There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java. • Object-oriented • Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our software as a combination of different types of objects that incorporate both data and behavior. • Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules. • Basic concepts of OOPs are: • Object • Class • Inheritance • Polymorphism • Abstraction • Encapsulation
  • 17.
    Platform Independent • Javais platform independent because it is different from other languages like C, C++, etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in which a program runs. • There are two types of platforms software-based and hardware-based. Java provides a software-based platform. Secured • Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because: • No explicit pointer • Java Programs run inside a virtual machine sandbox
  • 18.
    • Classloader: Classloaderin Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those that are imported from network sources. • Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects. • Security Manager: It determines what resources a class can access such as reading and writing to the local disk.
  • 19.
    Robust • The Englishmeaning of Robust is strong. Java is robust because: • It uses strong memory management. • There is a lack of pointers that avoids security problems. • Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore. • There are exception handling and the type checking mechanism in Java. All these points make Java robust. Architecture-neutral • Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed. • In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java. Portable • Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.
  • 20.
    High-performance • Java isfaster than other traditional interpreted programming languages because Java bytecode is "close" to native code. Distributed • Java is distributed because it facilitates users to create distributed applications in Java. This feature of Java makes us able to access files by calling the methods from any machine on the internet. Multi-threaded • A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc. Dynamic • Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. • Java supports dynamic compilation and automatic memory management (garbage collection).
  • 21.
    Java and WorldWide Web • World Wide Web is an open-ended information retrieval system designed to be used in the Internet’s distributed environment. This system contains what are known as Web Pages that provides both information and controls. Unlike a menu – driven system where we are guided through a particular direction using a decision tree structure, the Web system is open-ended and we can navigate to a new document in any direction. This is made possible with the help of a language called Hypertext Markup Language (HTML). Web pages contain HTML tags that enable us to find, retrieve, manipulate, and display documents worldwide. • Java was meant to be used in distributed environments such as Internet. Since, both the Web and Java share the same philosophy, Java could be easily incorporated into the Web system. Before Java, the World Wide Web was limited to the display of still images and texts. However, the incorporation of Java into the Web page has made it capable of supporting animation, graphics, games, and a wide range of special effects. With the support of Web, we can run Java program on someone else’s computer access from the Internet. • Java communicates with a Web page through a special tag called <APPLET>.
  • 22.
    • The usersends a request for an HTML document to the remote computer’s Web server. The Web server is a program that accepts a request, processes the request, and sends the request document. • The HTML document is returned to the user’s browser. The document contains the APPLET tag, which identifies the applet. • The corresponding applet byte code is transferred to the user’s computer. This bytecode had been previously created by the Java compiler using Java source code file for that applet. • The Java enabled browser on the user’s computer interprets the byte codes and provides output. • The user may have further interaction with the applet but with no further downloading from the provider’s Web server. This is because the bytecode contains all the information necessary to interpret the applet.
  • 23.
    Java Run TimeEnvironment • Java Runtime Environment (JRE) is an open-access software distribution that has a Java class library, specific tools, and a separate JVM. In Java, JRE is one of the interrelated components in the Java Development Kit (JDK). It is the most common environment available on devices for running Java programs. Java source code is compiled and converted to Java bytecode. If you want to run this bytecode on any platform, you need JRE. The JRE loads classes, check memory access and get system resources. JRE acts as a software layer on top of the operating system. • Components of Java JRE • Integration libraries include Java Database Connectivity (JDBC) • Java Naming, Interface Definition Language (IDL) • Directory Interface (JNDI) • Remote Method Invocation Over Internet Inter-Orb Protocol • Remote Method Invocation (RMI) • Scripting
  • 24.
    • Java VirtualMachine (JVM) consists of Java HotSpot Client and Server Virtual Machine. • User interface libraries include Swing, Java 2D, Abstract Window Toolkit (AWT), Accessibility, Image I/O, Print Service, Sound, drag, and Drop (DnD), and input methods. • Lang and util base libraries, which include lang and util, zip, Collections, Concurrency Utilities, management, Java Archive (JAR), instrument, reflection, versioning, Preferences API, Ref Objects, Logging, and Regular Expressions. • Other base libraries, including Java Management Extensions (JMX), Java Native Interface (JNI), Math, Networking, international support, input/output (I/O), Beans, Java Override Mechanism, Security, Serialization, extension mechanism, and Java for XML Processing (XML JAXP). • Deployment technologies such as Java Web Start, deployment, and Java plug-in.
  • 25.
    • Working ofJRE • Java Development Kit (JDK) and Java Runtime Environment (JRE) both interact with each other to create a sustainable runtime environment that enables Java-based applications to run seamlessly on any operating system. The JRE runtime architecture consists of the following elements as listed: • ClassLoader • ByteCode verifier • Interpreter • ClassLoader: Java ClassLoader dynamically loads all the classes necessary to run a Java program. Because classes are only loaded into memory whenever they are needed, the JRE uses ClassLoader will automate this process when needed. During the initialization of the JVM, three classLoaders are loaded: • Bootstrap class loader • Extensions class loader • System class loader
  • 26.
    • Bytecode Verifier:The bytecode checker ensures the format and precision of Java code before passing it to the interpreter. If the code violates system integrity or access rights, the class is considered corrupt and will not load. • Interpreter: After loading the byte code successfully, the Java interpreter creates an object of the Java virtual machine that allows the Java program to run natively on the underlying machine. • JRE has an object of JVM with it, development tools, and library classes. // Java class class hello{ // Main driver method public static void main(String[] args) { // Print statement System.out.println(“Hello World"); } } • O/p - Hello World • Once you write this program, you have to save it with .java extension. Compile your program. The output of the Java compiler is a byte-code which is platform independent. After compiling, the compiler generates a .class file which has the bytecode. The bytecode is platform independent and runs on any device having the JRE. From here, the work of JRE begins. To run any Java program, you need JRE. The flow of the bytecode to run is as diagram:
  • 27.
    Difference between JVM,JRE, and JDK. • JVM: JVM stands for Java Virtual Machine. JVM is used for running Java bytecode.Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one system and can expect it to run on any other Java-enabled system without any adjustment. This is all possible because of JVM. • JRE: JRE stands for Java Runtime Environment. JRE is made up of class libraries. • JDK: JDK stands for Java Development Kit. JDK contains the JRE with compiler, interpreter, debugger, and other tools. It provides features to run as well as develop Java Programs.
  • 28.
    JVM architecture • JVM(Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. • JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
  • 29.
    What is JVM Aspecification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Oracle and other companies. • Its implementation is known as JRE (Java Runtime Environment). • Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created. The JVM performs following operation: • Loads code • Verifies code • Executes code • Provides runtime environment • JVM provides definitions for the: • Memory area • Class file format • Register set • Garbage-collected heap • Fatal error reporting etc.
  • 30.
    1) Classloader Classloader isa 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 ClassLoader: 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 Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes etc. • 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. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.
  • 31.
    //Let's see anexample to print the classloader name public class ClassLoaderExample { public static void main(String[] args) { // Let's print the classloader name of current class. //Application/System classloader will load this class Class c=ClassLoaderExample.class; System.out.println(c.getClassLoader()); //If we print the classloader name of String, it will print null because it is an //in- built class which is found in rt.jar, so it is loaded by Bootstrap classloader System.out.println(String.class.getClassLoader()); } } O/p : sun.misc.Launcher$AppClassLoader@4e0e2f2a
  • 32.
    2) Class(Method) Area Itis memory block stores, class code, variable code ,runtime constant & Constructor of java. (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. Each thread has a private JVM stack, created at the same time as thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes. 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.
  • 33.
    7) Execution Engine Itcontains: A virtual processor Interpreter: Read bytecode stream then execute the instructions. 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. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU. 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.
  • 34.
    The requirement forJava Hello World Example For executing any Java program, the following software or application must be properly installed. 1. Install the JDK if you don't have installed it, download the JDK and install it. 2. Set path of the jdk/bin directory. http://www.javatpoint.com/ how-to-set-path-in-java 3. Create the Java program 4. Compile and run the Java program Creating Hello World Example. Let's create the hello java program: class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } } Save the above file as Simple.java. To compile: javac Simple.java To execute: java Simple Output: Hello Java
  • 35.
    • Compilation Flow: •When we compile Java program using javac tool, the Java compiler converts the source code into byte code. Java Code (Simple.java) Byte Code (Simple.class) Compiler
  • 36.
    Parameters used inFirst Java Program Let's see what is the meaning of class, public, static, void, main, String[], System.out.println(). • class keyword is used to declare a class in Java. • public keyword is an access modifier that represents visibility. Here Public means it is visible to all. • static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main() method is executed by the JVM, so it doesn't require creating an object to invoke the main() method. So, it saves memory. • void is the return type of the method. It means it doesn't return any value. • main represents the starting point of the program. • String[] args or String args[] is used for command line argument. • System.out.println() is used to print statement. Here, System is a class, out is an object of the PrintStream class, println() is a method of the PrintStream class.
  • 37.
    Java Program Structure •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 Behaviors
  • 38.
    Documentation Section • Thedocumentation 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. • Single-line Comment: It starts with a pair of forwarding slash (//). For example: //First Java Program • Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols. For example: /*It is an example of • multiline comment*/ • Documentation Comment: It starts with the delimiter (/**) and ends with */. For example: • /**It is an example of documentation comment*/
  • 39.
    Package Declaration • Thepackage 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 javapvpit; //where javapvpit is the package name package com. javapvpit; //where com is the root directory and javapvpit is the subdirectory 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. We use the 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
  • 40.
    Interface Section • Itis an optional section. We can create an interface in this section if required. We use the 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. We can use interface in classes by using the implements keyword. An interface can also be used with other interfaces by using the extends keyword. • It is used for total abstraction. Java doesn’t support multiple inheritance in case of class, by using interface. Any class extends only one class but any class can implement infinite no.of interfaces. • For example: interface car { void start(); void stop(); } Class Definition In this section, we define the class. It is vital part of a Java program. Without the class, we cannot create any Java program. A Java program may perform 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 { }
  • 41.
    Class Variables andConstants • In this section, we define variables and constants that are to be used later in the program. 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 In this section, we define the main() method. It is essential for all Java programs. Because the execution of all Java programs starts from the main() method. In other words, 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[]) { } public class Student //class definition { public static void main(String args[]) { //statements } }
  • 42.
    Methods and behavior Inthis section, we define the functionality of the program by using the methods. The methods are the set of instructions that we want to perform. These instructions execute at runtime and perform the specified task. For example: public class Demo //class definition { public static void main(String args[]) { void display() { System.out.println("Welcome to javatpoint"); } //statements } } /*Program name: Palindrome*/
  • 43.
    Java Tokens • InJava, the program contains classes and methods. Further, the methods contain the expressions and statements required to perform a specific operation. These statements and expressions are made up of tokens. In other words, we can say that the expression and statement is a set of tokens. The tokens are the small building blocks of a Java program that are meaningful to the Java compiler. Further, these two components contain variables, constants, and operators. What is token in Java? • The Java compiler breaks the line of code into text (words) is called Java tokens. These are the smallest element of the Java program. The Java compiler identified these words as tokens. These tokens are separated by the delimiters. It is useful for compilers to detect errors. Remember that the delimiters are not part of the Java tokens. • token <= identifier | keyword | separator | operator | literal | comment
  • 44.
    For example, considerthe following code. public class Demo { public static void main(String args[]) { System.out.println("javatpoint"); } } In the above code snippet, public, class, Demo, {, static, void, main, (, String, args, [, ], ), System, ., out, println, javatpoint, etc. are the Java tokens. The Java compiler translates these tokens into Java bytecode. Further, these bytecodes are executed inside the interpreted Java environment.
  • 45.
    Types of Tokens • Javatoken includes the following: • Keywords • Identifiers • Literals • Operators • Separators • Comments Keywords: These are the pre-defined reserved words of any programming language. Each keyword has a special meaning. It is always written in lower case. Java provides the following keywords: 01. abstract 02. boolean 03. byte 04. break 05. class 06. case 07. catch 08. char 09. continue 10. default 11. do 12. double 13. else 14. extends 15. final 16. finally 17. float 18. for 19. if 20. implements 21. import 22. instanceof 23. int 24. interface 25. long 26. native 27. new 28. package 29. private 30. protected 31. public 32. return 33. short 34. static 35. super 36. switch 37. synchronized 38. this 39. thro 40. throws 41. transient 42. try 43. void 44. volatile 45. while 46. assert 47. const 48. enum 49. goto 50. strictfp
  • 46.
    • Identifier: Identifiersare used to name a variable, constant, function, class, and array. It usually defined by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also known as a special kind of identifier that is used in the goto statement. Remember that the identifier name must be different from the reserved keywords. There are some rules to declare identifiers are: • The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with digits but may contain digits. • The whitespace cannot be included in the identifier. Some valid identifiers are: PhoneNumber PRICE radius a a1 _phonenumber $circumference jagged_array 12radius //invalid
  • 47.
    •Literals: In programmingliteral is a notation that represents a fixed value (constant) in the source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the programmer. Once it has been defined cannot be changed. Java provides five types of literals are as follows: •Integer •Floating Point •Character •String •Boolean
  • 48.
    • Operators: Inprogramming, operators are the special symbol that tells the compiler to perform a special operation. Java provides different types of operators that can be classified according to the functionality they provide. There are eight types of operators in Java, are as follows: • Arithmetic Operators • Assignment Operators • Relational Operators • Unary Operators • Logical Operators • Ternary Operators • Bitwise Operators • Shift Operators Operator Symbols Arithmetic + , - , / , * , % Unary ++ , - - , ! Assignment = , += , -= , *= , /= , %= , ^= Relational ==, != , < , >, <= , >= Logical && , || Ternary (Condition) ? (Statement1) : (Statement2); Bitwise & , | , ^ , ~
  • 49.
    • Separators: Theseparators in Java is also known as punctuators. There are nine separators in Java, are as follows: • separator <= ; | , | . | ( | ) | { | } | [ | ] • Note that the first three separators (; , and .) are tokens that separate other tokens, and the last six (3 pairs of braces) separators are also known as delimiters. For example, Math.pow(9, 3); contains nine tokens. • Square Brackets []: It is used to define array elements. A pair of square brackets represents the single-dimensional array, two pairs of square brackets represent the two-dimensional array. • Parentheses (): It is used to call the functions and parsing the parameters. • Curly Braces {}: The curly braces denote the starting and ending of a code block. • Comma (,): It is used to separate two values, statements, and parameters. • Assignment Operator (=): It is used to assign a variable and constant. • Semicolon (;): It is the symbol that can be found at end of the statements. It separates the two statements. • Period (.): It separates the package name form the sub-packages and class. It also separates a variable or method from a reference variable.
  • 50.
    •Comments: Comments allowus to specify information about the program inside our Java code. Java compiler recognizes these comments as tokens but excludes it form further processing. The Java compiler treats comments as whitespaces. Java provides the following two types of comments: •Line Oriented: It begins with a pair of forwarding slashes (//). •Block-Oriented: It begins with /* and continues until it founds */.
  • 51.
    Java Statements • Statementsare roughly equivalent to sentences in natural languages. In general, statements are just like English sentences that make valid sense. • What is statement in Java? • In Java, a statement is an executable instruction that tells the compiler what to perform. It forms a complete command to be executed and can include one or more expressions. A sentence forms a complete idea that can include one or more clauses. Types of Statements • Expression Statements • Declaration Statements • Control Statements
  • 52.
    Expression Statements • Expressionis an essential building block of any Java program. Generally, it is used to generate a new value. Sometimes, we can also assign a value to a variable. In Java, expression is the combination of values, variables, operators, and method calls. • There are three types of expressions in Java: • Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2. Note that the expression enclosed in the parentheses will be evaluate first, after that rest of the expression. • Expressions that assign a value. For example, number = 90, pi = 3.14. • Expression that neither produces any result nor assigns a value. For example, increment or decrement a value by using increment or decrement operator respectively, method invocation, etc. These expressions modify the value of a variable or state (memory) of a program. For example, count++, int sum = a + b; The expression changes only the value of the variable sum. The value of variables a and b do not change, so it is also a side effect.
  • 53.
    Declaration Statements In declarationstatements, we declare variables and constants by specifying their data type and name. A variable holds a value that is going to use in the Java program. For example: • int quantity; • boolean flag; • String message; Also, we can initialize a value to a variable. For example: • int quantity = 20; • boolean flag = false; • String message = "Hello"; Java also allows us to declare multiple variables in a single declaration statement. Note that all the variables must be of the same data type. • int quantity, batch_number, lot_number; • boolean flag = false, isContains = true; • String message = "Hello", how are you;
  • 54.
    Control Statement • Controlstatements decide the flow (order or sequence of execution of statements) of a Java program. In Java, statements are parsed from top to bottom. Therefore, using the control flow statements can interrupt a particular section of a program based on a certain condition.
  • 55.
    • Conditional orSelection Statements • if Statement • if-else statement • if-else-if statement • switch statement • Loop or Iterative Statements • for Loop • while Loop • do-while Loop • for-each Loop • Flow Control or Jump Statements • return • continue • break Example of Statement //declaration statement int number; //expression statement number = 412; //control flow statement if (number > 10 ) { //expression statement System.out.println(number + " is greater than 100"); }
  • 56.
    Java Constants As thename suggests, a constant is an entity in programming that is immutable. In other words, the value that cannot be changed. What is constant? • Constant is a value that cannot be changed after assigning it. Java does not directly support the constants. There is an alternative way to define the constants in Java by using the non-access modifiers static and final. How to declare constant in Java? • In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-access modifiers. According to the Java naming convention the identifier name must be in capital letters. Static and Final Modifiers • The purpose to use the static modifier is to manage the memory. • It also allows the variable to be available without loading any instance of the class in which it is defined. • The final modifier represents that the value of the variable cannot be changed. It also makes the primitive data type immutable or unchangeable.
  • 57.
    The syntax todeclare a constant is as follows: •static final datatype identifier_name=value; •For example, price is a variable that we want to make constant. •static final double PRICE=432.78; •Where static and final are the non-access modifiers. The double is the data type and PRICE is the identifier name in which the value 432.78 is assigned. •In the above statement, the static modifier causes the variable to be available without an instance of its defining class being loaded and the final modifier makes the variable fixed.
  • 58.
    Why we useboth static and final modifiers to declare a constant? • If we declare a variable as static, all the objects of the class (in which constant is defined) will be able to access the variable and can be changed its value. To overcome this problem, we use the final modifier with a static modifier. • When the variable defined as final, the multiple instances of the same constant value will be created for every different object which is not desirable. • When we use static and final modifiers together, the variable remains static and can be initialized once. Therefore, to declare a variable as constant, we use both static and final modifiers. It shares a common memory location for all objects of its containing class.
  • 59.
    Why we useconstants? • The use of constants in programming makes the program easy and understandable which can be easily understood by others. It also affects the performance because a constant variable is cached by both JVM and the application. Points to Remember: • Write the identifier name in capital letters that we want to declare as constant. For example, MAX=12. • If we use the private access-specifier before the constant name, the value of the constant cannot be changed in that particular class. • If we use the public access-specifier before the constant name, the value of the constant can be changed in the program.
  • 60.
    Enum : Itis a special data types that consists of a set of pre- defined named values separated by commas •Using Enumeration (Enum) as Constant •It is the same as the final variables. •It is a list of constants. •Java provides the enum keyword to define the enumeration. •It defines a class type by making enumeration in the class that may contain instance variables, methods, and constructors.
  • 61.
    Example of Enumeration(Dopractical) public class EnumExample { //defining the enum public enum Color {Red, Green, Blue, Purple, Black, White, Pink, Gray} public static void main(String[] args) { //traversing the enum for (Color c : Color.values()) System.out.println(c); } } Output:
  • 62.
    Variables- Declaration ,Giving values & Scope of variables • Variable Declaration is a statement that provides the variable name and its type, allowing the program to allocate memory for storing values. Importance of Variable Declaration: • Memory Allocation: When we declare a variable, we tell the computer to reserve some space in memory. This space is where the data associated with the variable will be stored. • Data Type Specification: Variable declaration also involves specifying the type of data the variable will hold (like a number, text, etc.). This helps the computer know how much memory to allocate for the variable. • Code Readability and Maintenance: Declaring variables makes our code easier to read and maintain. It gives meaningful names to data, which makes the code self-explanatory. • Avoiding Errors: If we try to use a variable that hasn’t been declared, the computer won’t know what we’re referring to, and this will lead to an error. • Scope Definition: Variable declaration defines the scope of the variable, i.e., the part of the code where the variable can be accessed.
  • 63.
    • Variable Declarationin Java: // Declaring an integer variable named 'a' int a; // Declaring a float variable named 'b' float b; // Declaring a character variable named 'c' char c; How to Initialize Variables in Java? It can be perceived with the help of 3 components that are as follows: datatype: Type of data that can be stored in this variable. variable_name: Name given to the variable. value: It is the initial value stored in the variable. Types of Variables in Java Local Variables Instance Variables Static Variables
  • 64.
    • 1. LocalVariables A variable defined within a block or method or constructor is called a local variable. The Local variable is created at the time of declaration and destroyed after exiting from the block or when the call returns from the function. The scope of these variables exists only within the block in which the variables are declared, i.e., we can access these variables only within that block. Initialization of the local variable is mandatory before using it in the defined scope. // Local Variables - Java Program to implement import java.io.*; class PVP { public static void main(String[] args) { int var = 10; // Declared a Local Variable System.out.println("Local Variable: " + var); // This variable is local to this main method only } }
  • 65.
    2. Instance Variables •Instance variables are non-static variables and are declared in a class outside of any method, constructor, or block. • As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. • Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier, then the default access specifier will be used. • Initialization of an instance variable is not mandatory. Its default value is dependent on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc. • Instance variables can be accessed only by creating objects. • We initialize instance variables using constructors while creating an object.
  • 67.
    • The statickeyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. • The static can be: • Variable (also known as a class variable) • Method (also known as a class method) • Block • Nested class Java static variable • If you declare any variable as static, it is known as a static variable. • The static variable gets memory only once in the class area at the time of class loading. • It makes your program memory efficient (i.e., it saves memory).
  • 68.
    class Student{ int rollno; Stringname; String college="ITS"; } Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to the common property of all objects. If we make it static, this field will get the memory only once. //Java Program to demonstrate the use of static variable class Student{ int rollno;//instance variable String name; static String college ="ITS";//static variable
  • 69.
    3. Static Variables •Static variables are also known as class variables. • These variables are declared similarly to instance variables. The difference is that static variables are declared using the static keyword within a class outside of any method, constructor, or block. • Unlike instance variables, we can only have one copy of a static variable per class, irrespective of how many objects we create. • Static variables are created at the start of program execution and destroyed automatically when execution ends. • Initialization of a static variable is not mandatory. Its default value is dependent on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc. • If we access a static variable like an instance variable (through an object), the compiler will show a warning message, which won’t halt the program. The compiler will replace the object name with the class name automatically. • If we access a static variable without the class name, the compiler will automatically append the class name. But for accessing the static variable of a different class, we must mention the class name as 2 different classes might have a static variable with the same name. • Static variables cannot be declared locally inside an instance method. • Static blocks can be used to initialize static variables.
  • 70.
    • Differences Betweenthe Instance Variables and the Static Variables • Each object will have its own copy of an instance variable, whereas we can only have one copy of a static variable per class, irrespective of how many objects we create. Thus, static variables are good for memory management. • Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of the instance variable. In the case of a static variable, changes will be reflected in other objects as static variables are common to all objects of a class. • We can access instance variables through object references, and static variables can be accessed directly using the class name. • Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed. Static variables are created when the program starts and destroyed when the program stops.
  • 71.
    Array • Normally, anarray is a collection of similar type of elements which has continuous memory location. • Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. • Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on. • Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator. • We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
  • 72.
    Advantages • Code Optimization:It makes the code optimized, we can retrieve or sort the data efficiently. • Random access: We can get any data located at an index position. Disadvantages • Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.
  • 73.
    //Java Program toillustrate how to declare, instantiate, initialize //and traverse the Java array. class Testarray{ public static void main(String args[]){ int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //traversing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }}
  • 74.
    Symbolic constant • InJava, a symbolic constant is a named constant value defined once and used throughout a program. Symbolic constants are declared using the final keyword. • Which indicates that the value cannot be changed once it is initialized. • The naming convention for symbolic constants is to use all capital letters with underscores separating words. Syntax of Symbolic Constants • final data_type CONSTANT_NAME = value; Initializing a symbolic constant: • final double PI = 3.14159;
  • 75.
    // Java Programto print an Array (Do practical) import java.io.*; public class Example { public static final int MAX_SIZE = 10; public static void main(String[] args) { int[] array = new int[MAX_SIZE]; for (int i = 0; i < MAX_SIZE; i++) { array[i] = i * 2; } System.out.print("Array: "); for (int i = 0; i < MAX_SIZE; i++) { System.out.print(array[i] + " "); } System.out.println(); } } Array: 0 2 4 6 8 10 12 14 16 18
  • 76.
    Type Casting inJava • In Java, type casting is a method or process that converts a data type into another data type in both ways manually and automatically. The automatic conversion is done by the compiler and manual conversion performed by the programmer.
  • 77.
    Type casting • Converta value from one data type to another data type is known as type casting. Types of Type Casting There are two types of type casting: • Widening Type Casting • Narrowing Type Casting • Widening Type Casting Converting a lower data type into a higher one is called widening type casting. It is also known as implicit conversion or casting down. It is done automatically. It is safe because there is no chance to lose data. It takes place when: • Both data types must be compatible with each other. • The target type must be larger than the source type. • Narrowing Type Casting • Converting a higher data type into a lower one is called narrowing type casting. It is also known as explicit conversion or casting up. It is done manually by the programmer. If we do not perform casting then the compiler reports a compile-time error.
  • 78.
    public class WideningTypeCastingExample {public static void main(String[] args) { int x = 7; //automatically converts the integer type into long type long y = x; //automatically converts the long type into float type float z = y; System.out.println("Before conversion, int value "+x); System.out.println("After conversion, long value "+y); System.out.println("After conversion, float value "+z); } } Output Before conversion, the value is: 7 After conversion, the long value is: 7 After conversion, the float value is: 7.0
  • 79.
    public class NarrowingTypeCastingExample {public static void main(String args[]) { double d = 166.66; //converting double data type into long data type long l = (long)d; //converting long data type into int data type int i = (int)l; System.out.println("Before conversion: "+d); //fractional part lost System.out.println("After conversion into long type: "+l); //fractional part lost System.out.println("After conversion into int type: "+i); } } Output Before conversion: 166.66 After conversion into long type: 166 After conversion into int type: 166
  • 80.
    Default Values Assignedto Primitive Data Types in Java • In Java, when a variable is declared but not initialized, it is assigned a default value based on its data type. The default values for the primitive data types in Java are as follows: • byte: 0 • short: 0 • int: 0 • long: 0L • float: 0.0f • double: 0.0d • char: ‘u0000’ (null character) • boolean: false • It is important to note that these default values are only assigned if the variable is not explicitly initialized with a value. If a variable is initialized with a value, that value will be used instead of the default. • Primitive data types are built-in data types in java and can be used directly without using any new keyword. As we know primitive data types are treated differently by java cause of which the wrapper class concept also comes into play. But here we will be entirely focussing on data types. So, in java, there are 8 primitive data types as shown in the table below with their corresponding sizes.
  • 81.
    Data Type Size Byte1 byte Short 2 bytes Int 4 bytes Long 8 bytes Float 4 bytes Double 8 bytes Boolean 1 bit Char 1 byte Now, here default values are values assigned by the compiler to the variables which are declared but not initialized or given a value. They are different according to the return type of data type which is shown below where default values assigned to variables of different primitive data types are given in the table. However, relying on such default values is not considered a good programming style.
  • 82.
    Operator Precedenc e in Java (Highest toLowest) Category Operators Associativity Postfix ++ - - Left to right Unary + - ! ~ ++ - - Right to left Multiplicative * / % Left to right Additive + - Left to right Shift << >> Left to right Relational < <= > >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
  • 83.
    Operator Precedence Vs.Operator Associativity • The operator's precedence refers to the order in which operators are evaluated within an expression whereas associativity refers to the order in which the consecutive operators within the same group are carried out.
  • 84.
    Mathematical functions • JavaMath class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc. • Unlike some of the StrictMath class numeric methods, all implementations of the equivalent function of Math class can't define to return the bit-for-bit same results. This relaxation permits implementation with better-performance where strict reproducibility is not required. • If the size is int or long and the results overflow the range of value, the methods addExact(), subtractExact(), multiplyExact(), and toIntExact() throw an ArithmeticException. • For other arithmetic operations like increment, decrement, divide, absolute value, and negation overflow occur only with a specific minimum or maximum value. It should be checked against the maximum and minimum value as appropriate.
  • 85.
    Method Description Math.abs() Itwill return the Absolute value of the given value. Math.max() It returns the Largest of two values. Math.min() It is used to return the Smallest of two values. Math.round() It is used to round of the decimal numbers to the nearest value. Math.sqrt() It is used to return the square root of a number. Math.cbrt() It is used to return the cube root of a number. Math.pow() It returns the value of first argument raised to the power to second argument. Math.signum() It is used to find the sign of a given value. Math.ceil() It is used to find the smallest integer value that is greater than or equal to the argument or mathematical integer. Math.copySign() It is used to find the Absolute value of first argument along with sign specified in second argument. Math.nextAfter() It is used to return the floating-point number adjacent to the first argument in the direction of the second argument. Math.nextUp() It returns the floating-point value adjacent to d in the direction of positive infinity. Math.nextDown() It returns the floating-point value adjacent to d in the direction of negative infinity. Math.floor() It is used to find the largest integer value which is less than or equal to the argument and is equal to the mathematical integer of a double value.
  • 86.
    Math.random() It returnsa double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Math.rint() It returns the double value that is closest to the given argument and equal to mathematical integer. Math.hypot() It returns sqrt(x2 +y2 ) without intermediate overflow or underflow. Math.ulp() It returns the size of an ulp of the argument. Math.getExponent() It is used to return the unbiased exponent used in the representation of a value. Math.IEEEremainder() It is used to calculate the remainder operation on two arguments as prescribed by the IEEE 754 standard and returns value. Math.addExact() It is used to return the sum of its arguments, throwing an exception if the result overflows an int or long. Math.subtractExact() It returns the difference of the arguments, throwing an exception if the result overflows an int. Math.multiplyExact() It is used to return the product of the arguments, throwing an exception if the result overflows an int or long. Math.incrementExact() It returns the argument incremented by one, throwing an exception if the result overflows an int. Math.decrementExact( ) It is used to return the argument decremented by one, throwing an exception if the result overflows an int or long. Math.negateExact() It is used to return the negation of the argument, throwing an exception if the result
  • 87.
    Logarithmic Math Methods MethodDescription Math.log() It returns the natural logarithm of a double value. Math.log10() It is used to return the base 10 logarithm of a double value. Math.log1p() It returns the natural logarithm of the sum of the argument and 1. Math.exp() It returns E raised to the power of a double value, where E is Euler's number and it is approximately equal to 2.71828. Math.expm1() It is used to calculate the power of E and subtract one from it.
  • 88.
    Trigonometric Math Methods MethodDescription Math.sin() It is used to return the trigonometric Sine value of a Given double value. Math.cos() It is used to return the trigonometric Cosine value of a Given double value. Math.tan() It is used to return the trigonometric Tangent value of a Given double value. Math.asin() It is used to return the trigonometric Arc Sine value of a Given double value Math.acos() It is used to return the trigonometric Arc Cosine value of a Given double value.