0% found this document useful (0 votes)
10 views

Java Notes UNIT-1

The document outlines the vision and mission of an educational institute focused on empowering individuals through holistic education, particularly in Object-Oriented Programming (OOP) with Java. It details the course structure, outcomes, and key concepts of OOP, including principles like encapsulation, inheritance, and polymorphism, as well as advantages and applications of OOP. The document serves as a comprehensive guide for students to understand Java programming fundamentals and the significance of OOP in software development.

Uploaded by

Uday Gowda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java Notes UNIT-1

The document outlines the vision and mission of an educational institute focused on empowering individuals through holistic education, particularly in Object-Oriented Programming (OOP) with Java. It details the course structure, outcomes, and key concepts of OOP, including principles like encapsulation, inheritance, and polymorphism, as well as advantages and applications of OOP. The document serves as a comprehensive guide for students to understand Java programming fundamentals and the significance of OOP in software development.

Uploaded by

Uday Gowda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

VISION OF THE INSTITUTE

Empower the individuals and society at large through educational excellence; sensitize them for a life
dedicated to the service of fellow human beings and mother land.
MISSION OF THE INSTITUTE
To impact holistic education that enables the students to become socially responsive and useful, with
roots firm on traditional and cultural values; and to hone their skills to accept challenges and respond to
opportunities in a global scenario.

Lecture Notes on: Object Oriented Programming with Java


Course Code: CAM22T
No. of Credits: 03
Contact Hours: 44 Hours (3 hours per week)
Formative Assessment Marks: 20
Summative Assessment Marks: 80
Examination Duration: 03 hours

Course Outcomes (COs):


On successful completion of this course, students will be able to:
1. Understand the Java programming fundamentals.
2. Describe with examples of basic Java OOP concepts.
3. Understand the Java Interfaces and Packages.
4. Deliberate the Details of Multithreading, Exception Handling & File Handling
5. Design GUI applications using tools like AWT.

Prepared by:
Asst. prof. BHOOMIKA M M
Department of Computer Applications.
Syllabus:
UNIT 1
Fundamentals of Object-oriented Programming: 11 Hours
Object-oriented Paradigm, Basic Principles of Object-oriented Programming, Advantages of
Object-Oriented Programming, Applications of Object-Oriented Programming.
Introduction to Java Language:
Java History, Features, Overview, Difference between C, C+ + and Java, Java Environment-
JDK, JVM, JRE and API, Java Program Structure, Java Tokens, Implementing a Java
Program, Command Line Arguments.
Java Programming Fundamentals:
Data types, Variables & Constants, Keywords & Naming Conventions, Type Casting,
Operators and Expressions, Control Structures, Jumping Statements.
UNIT 2
Classes & Objects 11 Hours
Basics of Objects and Classes, Constructors, Access Modifiers, Method Overloading,
Overloading Constructors, Static members, this keyword.
Arrays: One dimensional Arrays, Two dimensional Arrays, Array of Objects.
Strings: String Handling functions.
UNIT 3
Multithreading in Java 11 Hours
Concepts of Thread, Thread Life Cycle, Creating Threads & Implementing Runnable
Interface, Thread Synchronization & Thread Priority.
Exception Handling
Concepts of Exception, Different Types of Exceptions, Creating User-Defined Exceptions
Using Try-Catch-Finally-Throw Blocks, Nested Try, Catch, Throw, and Throws Blocks.
UNIT 4
File Handling: I/O Handling, I/O Streams, Types of Files, Byte Stream, Binary I/O Classes 11 Hours
& Its Hierarchy, File Input Stream & File Output Stream Classes, Object I/O Classes.
Event Handling & GUI programming: Event Handling, Event Types, Event Handling
Mechanism, Keyboard & Mouse Handling, Introduction to AWT & GUI basics, AWT
hierarchy of classes, AWT controls – Frames, Panels, Layout managers & other controls of
AWT.

Reference Books:
1. D.S. Guru, M.T. Somashekara, & K.S. Manjunatha, Object Oriented Programming with Java, PHI
Learning, 2017.
2. E Balagurusamy, Programming with JAVA, TMH, 2007
3. Herbert Schildt, Java 7, The Complete Reference, 8th Edition, 2009.
UNIT 1

Introduction to Java:
Java is a high-level programming language originally developed by Sun Microsystems which was initiated by
James Gosling and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX.
Java is used to develop mobile apps, desktop apps, web apps, web servers, games, and enterprise-level
systems
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread
popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for
Enterprise Applications, J2ME for Mobile Applications. The new J2 versions were renamed as Java SE, Java
EE, and Java ME respectively. JDK 23 is the latest version of Java.
Java is guaranteed to be Write Once, Run Anywhere. Popular platforms like LinkedIn,
Amazon, and Netflix rely on Java for their back-end architecture, showcasing its stability and scalability across
different environments.

Fundamentals of Object-oriented Programming


Object-oriented programming (OOP) is a fundamental programming paradigm based on the concept of _
“objects” _. These objects can contain data in the form of fields (often known as attributes or properties) and
code in the form of procedures (often known as methods).
The core concept of the object-oriented approach is to break complex problems into smaller objects.
Simula and Smalltalk are considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object is known as truly object-oriented programming
language.
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology
or paradigm to design a program using classes and objects. It simplifies the software development and
maintenance by providing some concepts:

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object-oriented Paradigm
A paradigm is a fundamental model, pattern, or approach that defines the way something is structured or
performed. It provides a framework for thinking, working, or solving problems in a particular domain.
Object-Oriented Paradigm (OOP)
The Object-Oriented Paradigm (OOP) is a programming paradigm that focuses on organizing code using
objects and classes rather than functions and logic. It provides a structured way of designing and implementing
software systems by modeling real-world entities as objects.

Imperative Language
The programmers instruct the machine to perform a task by writing step-by-step instructions including
variables, conditions, loops etc.

Procedural Oriented
Procedural language breaks down a task into a collection of procedures(aka. subroutines, functions) to
perform a task. It maintains global variables to manage the state of the system. C, BASIC, and ALGOL
etc belong to the procedural-oriented paradigm.
Object Oriented
Object Oriented language breaks down a task into objects that expose behaviour(method) and data
(member or attribute), objects communicate with each other through message-passing techniques to
accomplish a given task. C++, Java, C#, Kotlin etc belong to the object-oriented paradigm

Declarative Language
The programmers instruct the machine What to perform without any instructions. The programmer asks for
the desired result.
Functional

Functional programming contains only functions without mutating the state or data. It means that there
are no global data/variables. Composing and applying function is the main driving force in this
paradigm. A function can take another as an argument and return a new function.
Logical
The Logical paradigm has its foundations in mathematical logic in which program statements express
facts and rules. Rules are written as logical clauses. The engine infers the answer to the user’s query
by using unification and backtracking techniques.

Basic Principles of Object-Oriented Programming

Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An Object is an instance
of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created)
memory is allocated. An object has an identity, state, and behaviour. Each object contains data and code to
manipulate the data. Objects can interact without having to know details of each other’s data or code, it is
sufficient to know the type of message accepted and type of response returned by the objects.
For example, “Dog” is a real-life Object, which has some characteristics like color, Breed, Bark, Sleep, and
Eats.

Class
Collection of objects is called class. It is a logical entity. A class is a user-defined data type. It consists of data
members and member functions, which can be accessed and used by creating an instance of that class. It
represents the set of properties or methods that are common to all objects of one type. A class is like a blueprint
for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brands but all
of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range,
etc. So here, Car is the class, and wheels, speed limits, mileage are their properties

Data Abstraction:
Data abstraction is one of the most essential and important features of object-oriented programming. Data
abstraction refers to providing only essential information about the data to the outside world, hiding the
background details or implementation. Consider a real-life example of a man driving a car. The man only
knows that pressing the accelerators will increase the speed of the car or applying brakes will stop the car, but
he does not know about how on pressing the accelerator the speed is increasing, he does not know about the
inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is what
abstraction is.
Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together
code and the data it manipulates. In Encapsulation, the variables or data of a class are hidden from any other
class and can be accessed only through any member function of their class in which they are declared. As in
encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
Inheritance:
Inheritance is an important pillar of OOP (Object-Oriented Programming). The capability of a class to derive
properties and characteristics from another class is called Inheritance. When we write a class, we inherit
properties from other classes. So, when we create a class, we do not need to write all the properties and
functions again and again, as these can be inherited from another class that possesses it. Inheritance allows
the user to reuse the code whenever possible and reduce its redundancy.

Polymorphism:
The word polymorphism means having many forms. In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one form.

Dynamic Binding:
In dynamic binding, the code to be executed in response to the function call is decided at runtime. Dynamic
binding means that the code associated with a given procedure call is not known until the time of the call at
run time. Dynamic Method Binding One of the main advantages of inheritance is that some derived class D
has all the members of its base class B. Once D is not hiding any of the public members of B, then an object
of D can represent B in any context where a B could be used. This feature is known as subtype polymorphism.

Message Passing:
It is a form of communication used in object-oriented programming as well as parallel programming. Objects
communicate with one another by sending and receiving information to each other. A message for an object
is a request for execution of a procedure and therefore will invoke a function in the receiving object that
generates the desired results. Message passing involves specifying the name of the object, the name of the
function, and the information to be sent.

Association
An association is a relationship between two distinct classes that are established with the aid of their objects.
One-to-one, one-to-many, many-to-one, and many-to-many associations are all possible. An association is a
connection between two things. The diversity between objects is defined by one of Java’s OOP concepts.

Aggregation
In this method, each object has a distinct lifecycle. Ownership, however, prevents the child object from being
a part of another parent object. Java aggregation depicts the link between an object that contains other objects
and is a weak association. This illustrates the connection between a component and a whole, where a part can
exist without a whole.

Composition
Composition is an association that depicts a relationship between a part and a whole in which a part cannot
exist without a whole.

Constructors and methods


A constructor is a specific kind of subroutine called to create an object. It sets up the new object for use and
frequently accepts arguments from the constructor to set up necessary member variables. In OOP, a method
is a procedure connected to a message and an object. An object’s state data and behaviour make up its interface,
which describes how any of its numerous consumers may use it. A method is a consumer-parameterized object
activity.

Why do we need object-oriented programming?

• To make the development and maintenance of projects more effortless.


• To provide the feature of data hiding that is good for security concerns.
• We can solve real-world problems if we are using object-oriented programming.
• It ensures code reusability.
• It lets us write generic code: which will work with a range of data, so we don’t have to write basic stuff over
and over again.

Advantages of Object-Oriented Programming


1. Modularity and Code Reusability
OOP encourages modular design by breaking down a system into smaller, manageable pieces (classes and
objects).
Code can be reused across applications through inheritance and polymorphism, reducing development time
and effort.
Example: A class like Vehicle can be reused and extended to create Car, Bike, or Truck classes.

2. Improved Code Maintainability


Encapsulation allows for changes in one part of the program without affecting other parts.
Clearly defined interfaces and modularity make debugging, testing, and updating the code more manageable.

3. Data Security and Integrity


By encapsulating data within classes and controlling access through methods (getters/setters), OOP ensures
that only authorized parts of the program can modify or access critical data.
This reduces the likelihood of errors caused by unintended modifications.
Example: Private fields in a class ensure sensitive information is hidden from external code.

4. Faster Development Through Abstraction


Abstraction hides complex implementation details, allowing developers to focus on solving specific problems
rather than worrying about lower-level details.
Abstract classes and interfaces provide a blueprint for creating objects.

5. Scalability and Flexibility


OOP makes it easier to scale applications by adding new features or modifying existing ones without affecting
the overall structure.
Polymorphism allows methods to adapt based on the context, enabling flexible code.
Example: In a banking system, you can add a new account type (e.g., Savings Account) without modifying
the base Account class.

6. Enhanced Collaboration in Teams


By clearly defining class responsibilities, OOP makes it easier for team members to work on different parts
of a system independently.
For example, one developer can focus on designing a Payment Processor class while another works on
Transaction
.
7. Real-World Modelling
OOP concepts like classes and objects closely mirror real-world entities, making it easier to design systems
that are intuitive and aligned with real-world scenarios.
For example, a Car class might have attributes like speed and colour, and methods like accelerate() or brake().

8. Improved Productivity
Reusable code, modular design, and abstraction lead to faster development cycles and reduced development
costs.
Libraries and frameworks based on OOP (e.g., Java libraries, .NET frameworks) provide ready-to-use
components.

9. Easier Debugging
With modular code and encapsulation, errors are isolated to specific classes or methods, making it easier to
identify and fix bugs.

10. Support for Advanced Features


OOP supports advanced programming features like multithreading, event-driven programming, and graphical
user interfaces (GUIs).
Languages like Java, C++, Python, and C# leverage OOP for powerful application development.

Disadvantages

• OOP can introduce unnecessary complexity for small or simple programs, as defining classes, objects,
and relationships may feel excessive for straightforward tasks.

• OOP systems often require more memory and processing power due to features like dynamic dispatch,
inheritance hierarchies, and the creation of multiple objects.

• or small or quick applications, the setup required for creating classes, objects, and hierarchies can slow
down development compared to procedural programming.

Applications of Object-Oriented Programming

• Real-Time System design: Real-time system inherits complexities and makes it difficult to build
them. OOP techniques make it easier to handle those complexities.
• Hypertext and Hypermedia: Hypertext is similar to regular text as it can be stored, searched, and
edited easily. Hypermedia on the other hand is a superset of hypertext. OOP also helps in laying the
framework for hypertext and hypermedia.

• AI Expert System: These are computer application that is developed to solve complex problems
which are far beyond the human brain. OOP helps to develop such an AI expert System

• Office automation System: These include formal as well as informal electronic systems that primarily
concerned with information sharing and communication to and from people inside and outside the
organization. OOP also help in making office automation principle.

• Neural networking and parallel programming: It addresses the problem of prediction and
approximation of complex-time varying systems. OOP simplifies the entire process by simplifying the
approximation and prediction ability of the neural networking.

• Stimulation and modeling system: It is difficult to model complex systems due to varying
specifications of variables. Stimulating complex systems require modeling and understanding
interaction explicitly. OOP provides an appropriate approach for simplifying these complex models.

• Object-oriented database: The databases try to maintain a direct correspondence between the real
world and database object in order to let the object retain it identity and integrity.

• Client-server system: Object-oriented client-server system provides the IT infrastructure creating


object-oriented server internet (OCSI) applications.

• CIM/CAD/CAM systems: OOP can also be used in manufacturing and designing applications as it
allows people to reduce the efforts involved. For instance, it can be used while designing blueprints
and flowcharts. So, it makes it possible to produce these flowcharts and blueprint accurately.
Introduction to Java Language

Java is a class-based, object-oriented programming language that is designed to have as few


implementation dependencies as possible. It is intended to let application developers Write Once and Run
Anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the
need for recompilation. Java was developed by James Gosling at Sun Microsystems Inc. in May
1995 and later acquired by Oracle Corporation and is widely used for developing applications for desktop,
web, and mobile devices.

Java is known for its simplicity, robustness, and security features, making it a popular choice for enterprise-
level applications. Java applications are compiled to byte code that can run on any Java Virtual Machine. The
syntax of Java is similar to C/C++.

Java history
James Gosling and his team initially named their project "Greentalk" (.gt), later renaming it "Oak" after an
oak tree outside Gosling's office, symbolizing strength and being the national tree of several nations. However,
due to a trademark conflict with Oak Technologies, it was renamed "Java," inspired by coffee beans, during a
brainstorming session. Created to be robust, portable, platform-independent, and high-performance, Java was
recognized as one of TIME Magazine's Ten Best Products of 1995. Over time, it evolved from JDK 1.0 with
a few hundred classes to over 3,000 classes in J2SE 5, becoming vital in programming, mobile apps, and e-
business.

Version Release Date Major changes

JDK Beta 1995 ----

The Very first version was released on January 23, 1996. The
JDK 1.0 January 1996
principal stable variant, JDK 1.0.2, is called Java 1.

Was released on February 19, 1997. There were many


additions in JDK 1.1 as compared to version 1.0 such as
• A broad retooling of the AWT occasion show
JDK 1.1 February 1997 • Inner classes added to the language
• JavaBeans
• JDBC
• RMI
Version Release Date Major changes

“Play area” was the codename which was given to this form
and was released on 8th December 1998. Its real expansion
included: strictfp keyword
• the Swing graphical API was coordinated into the
centre classes
J2SE 1.2 December 1998
• Sun’s JVM was outfitted with a JIT compiler out of
the blue
• Java module
• Java IDL, an IDL usage for CORBA interoperability
• Collections system

Codename- “KESTREL” Release Date- 8th May 2000


Additions:
• HotSpot JVM included
J2SE 1.3 May 2000 • Java Naming and Directory Interface
• JPDA
• JavaSound
• Synthetic proxy classes

Codename- “Merlin” Release Date- 6th February 2002


Additions: Library improvements
• Regular expressions modelled after Perl regular
expressions
• The image I/O API for reading and writing images in
J2SE 1.4 February 2002 formats like JPEG and PNG
• Integrated XML parser and XSLT processor (JAXP)
(specified in JSR 5 and JSR 63)
• Preferences API (java.util.prefs)
Public Support and security updates for this version ended in
October 2008.

Codename- “Tiger” Release Date- “30th September 2004”


Originally numbered as 1.5 which is still used as its internal
version. Added several new language features such as:
J2SE 5.0 September 2004 • for-each loop
• Generics
• Autoboxing
• Var-args

Codename- “Mustang” Released Date- 11th December 2006


Packaged with a database supervisor and encourages the
utilization of scripting languages with the JVM. Replaced the
JAVA SE 6 December 2006 name J2SE with java SE and dropped the .0 from the version
number. Additions:
• Upgrade of JAXB to version 2.0: Including integration
of a StAX parser.
Version Release Date Major changes

• Support for pluggable annotations (JSR 269).


• JDBC 4.0 support (JSR 221)

Codename- “Dolphin” Release Date- 7th July 2011 Added


small language changes including strings in the switch. The
JVM was extended with support for dynamic languages.
JAVA SE 7 July 2011 Additions:
• Compressed 64-bit pointers.
• Binary Integer Literals.
• Upstream updates to XML and Unicode.

Released Date- 18th March 2014 Language level support for


JAVA SE 8 March 2014 lambda expressions and default methods and a new date and
time API inspired by Joda Time.

Release Date: 21st September 2017 Project Jigsaw: designing


and implementing a standard, a module system for the Java
JAVA SE 9 September 2017
SE platform, and to apply that system to the platform itself and
the JDK.

Released Date- 20th March Addition:


• Additional Unicode language-tag extensions
• Root certificates
JAVA SE 10 March 2018 • Thread-local handshakes
• Heap allocation on alternative memory devices
• Remove the native-header generation tool – javah.
• Consolidate the JDK forest into a single repository.

Released Date- 25th September, 2018 Additions-


• Dynamic class-file constants
• Epsilon: a no-op garbage collector
• The local-variable syntax for lambda parameters
JAVA SE 11 September 2018
• Low-overhead heap profiling
• HTTP client (standard)
• Transport Layer Security (TLS) 1.3
• Flight recorder

Released Date- 19th March 2019 Additions-


• Shenandoah: A Low-Pause-Time Garbage Collector
(Experimental)
JAVA SE 12 March 2019 • Microbenchmark Suite
• Switch Expressions (Preview)
• JVM Constants API
• One AArch64 Port, Not Two
Version Release Date Major changes

• Default CDS Archives

Released Date – 17th September 2019


Additions-
JAVA SE 13 September 2019 • Text Blocks (Multiline strings).
• Switch Expressions.
• Enhanced Thread-local handshakes.

Released Date – 17th March 2020


Additions-
JAVA SE 14 March 2020 • Records (new class type for data modeling).
• Pattern Matching for instance of.
• Helpful NullPointerExceptions.

Released Date – 15th September 2020


Additions-
JAVA SE 15 September 2020 • Sealed Classes.
• Hidden Classes.
• Foreign Function and Memory API (Incubator).

Released Date – 16th March 2021


Additions-
JAVA SE 16 March 2021 • Records (preview feature).
• Pattern Matching for switch (preview feature).
• Unix Domain Socket Channel (Incubator).

Released Date – 14th September 2021


Additions-
• Sealed Classes (finalized).
JAVA SE 17 September 2021
• Pattern Matching for instanceof (finalized).
• Strong encapsulation of JDK internals by default.
• New macOS rendering pipeline.
Features of Java
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role
in the popularity of this language. The features of Java are also known as Java buzzwords.

1. Platform Independent
Compiler converts source code to byte code and then the JVM executes the bytecode generated by the
compiler. This byte code can run on any platform be it Windows, Linux, or macOS which means if we compile
a program on Windows, then we can run it on Linux and vice versa. Each operating system has a
different JVM, but the output produced by all the OS is the same after the execution of the byte code. That
is why we call java a platform-independent language.

2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes. Organizing the program in the
terms of a collection of objects is a way of object-oriented programming, each of which represents an instance
of the class.
The four main concepts of Object-Oriented programming are:
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism

3. Simplicity
Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It eliminates complex
features like pointers and multiple inheritances, making it easier to write, debug, and maintain code.

4. Robustness
Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort into
checking errors as early as possible, that is why the java compiler is able to detect even those errors that are
not easy to detect by another programming language. The main features of java that make it robust are garbage
collection, exception handling, and memory allocation.

5. Security
Java do not have pointers, so we cannot access out-of-bound arrays i.e it shows ArrayIndexOutOfBound
Exception if we try to do so. That’s why several security flaws like stack corruption or buffer overflow are
impossible to exploit in Java. Also, java programs run in an environment that is independent of the OS
(operating system) environment which makes java programs more secure.
6. Distributed
We can create distributed applications using the java programming language. Remote Method Invocation and
Enterprise Java Beans are used for creating distributed applications in java. The java programs can be easily
distributed on one or more systems that are connected to each other through an internet connection.

7. Multithreading
Java supports multithreading, enabling the concurrent execution of multiple parts of a program. This feature
is particularly useful for applications that require high performance, such as games and real-time simulations.

8. Portability
As we know, java code written on one machine can be run on another machine. The platform-independent
feature of java in which its platform-independent bytecode can be taken to any platform for execution makes
java portable. WORA(Write Once Run Anywhere) makes java application to generates a ‘.class’ file that
corresponds to our applications(program) but contains code in binary format. It provides ease t architecture-
neutral ease as bytecode is not dependent on any machine architecture. It is the primary reason java is used in
the enterprising IT industry globally worldwide.

9. High Performance
Java architecture is defined in such a way that it reduces overhead during the runtime and at sometimes java
uses Just In Time (JIT) compiler where the compiler compiles code on-demand basis where it only compiles
those methods that are called making applications to execute faster.

Difference between C, C+ + and Java

Basis
SL.No C C++ Java

Origin The C language is The C++ language The Java


based on BCPL is based on the C programming
1 language. language is based
on both C and
C++.
Programming It is a procedural It is an object- It is a pure object-
Pattern language. oriented oriented
2
programming programming
language. language.
Approach It uses the top- It uses the bottom- It also uses the
3 down approach. up approach. bottom-up
approach.
Dynamic or Static It is a static It is also a static It is a dynamic
4 programming programming programming
language. language. language.
Code Execution The code is The code is The code is
5 executed directly. executed directly. executed by the
JVM.
Platform It is platform It is platform It is platform-
Dependency dependent. dependent. independent
6
because of byte
code
Translator It uses a compiler It also uses a Java uses both
only to translate compiler only to compiler and
the code into translate the code interpreter and it is
7
machine language. into machine also known as an
language. interpreted
language.
Source File The source file has The source file has The source file has
8
Extension a .c extension. a .cpp extension. a .java extension.
Pointer Concept It supports pointer. It also supports Java does not
pointer. support the pointer
9
concept because of
security.
It does not support It supports both It supports
Constructor/ constructor and constructor and constructors only
10 Destructor destructor. destructor.

Memory It uses the calloc(), It uses new and It uses a garbage


Management malloc(), free(), delete operator to collector to
11 and realloc() manage the manage the
methods to manage memory. memory.
the memory.
It is widely used to It is widely used It is used to
Used for develop drivers for system develop web
and operating programming. applications,
12 systems. mobile
applications, and
windows
applications.
Array Size An array should be An array should be An array can be
declared with size. declared with size. declared without
For example, int declaring the size.
13
num[10]. For example, int
num[].

Java Environment

JDK in Java
The Java Development Kit (JDK) is a cross-platformed software development environment that offers a
collection of tools and libraries necessary for developing Java-based software applications and applets. It is a
core package used in Java, along with the JVM (Java Virtual Machine) and the JRE (Java Runtime
Environment).
JDK=JRE+Development Tools

Contents of JDK

The JDK has a private Java Virtual Machine (JVM) and a few other resources necessary for the development
of a Java Application.

JDK contains:

• Java Runtime Environment (JRE),


• An interpreter/loader (Java),

• A compiler (javac),

• An archiver (jar) and many more.

The Java Runtime Environment in JDK is usually called Private Runtime because it is separated from the
regular JRE and has extra content. The Private Runtime in JDK contains a JVM and all the class libraries
present in the production environment, as well as additional libraries useful to developers, e.g,
internationalization libraries and the IDL libraries.

Most Popular JDKs:

• Oracle JDK: the most popular JDK and the main distributor of Java11,

• OpenJDK: Ready for use: JDK 15, JDK 14, and JMC,

• Azul Systems Zing: efficient and low latency JDK for Linux os,

• Azul Systems: based Zulu brand for Linux, Windows, Mac OS X,

• IBM J9 JDK: for AIX, Linux, Windows, and many other OS,

• Amazon Corretto: the newest option with the no-cost build of OpenJDK and long-term support.

JVM Architecture
JVM (Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls
the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop
Java code on one system and expect it to run on any other Java-enabled system without any adjustment.
This is all possible because of JVM.
When we compile a .java file, .class files(contains byte-code) with the same class names present
in .java file are generated by the Java compiler. This .class file goes into various steps when we run it.
These steps together describe the whole JVM.
1) Class loader

Class loader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is
loaded first by the class loader. There are three built-in class loaders in Java.

1. Bootstrap Class Loader: This is the first class loader which is the super class of Extension class
loader. 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.

2. Extension Class Loader: This is the child class loader of Bootstrap and parent class loader of System
classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.

3. System/Application Class Loader: This is the child class loader of Extension class loader. 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 class loader.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the
code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and
return.
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

1. A virtual processor

2. Interpreter: Read bytecode stream then execute the instructions.

3. 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.

Structure of Java Program


1. 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*/

2. The 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 javatpoint; //where javatpoint is the package name

package com.javatpoint; //where com is the root directory and javatpoint is the subdirectory

3. 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
4. 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.

For example:

interface car

void start();

void stop();

5. 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 conation more than one class definition. We use
the class keyword to define the class. The class is a blueprint of a Java program. It contains information
about user-defined methods, variables, and constants. Every Java program has at least one class that
contains the main() method.

For example:

class Student //class definition

6. 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;

7. 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[])

Example:

public class Student //class definition

public static void main(String args[])

//statements

8. 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
}
}

Example of Java program

Simple Java Program


import java.io.*;
public class Welcome
{
public static void main (String args[])
{
System.out.println (“welcome to Java Program”);
}
}
• public: It is access specifier and this method can be called from outside also.
• static: This main method must always declared as static because the whole program has
only one main method and without using object the main method can be executed by
using the class name.
• void: The main method does not return anything.
• main: - The main method similar to main function in c and c++. This main method call
first (execute first) by the interpreter to run the java program.
• String: It is built-in class under language package.
• args []: This is an array of type string. a command line argument holds the argument
in this array. System.out.println:
• System: It is a class which contains several useful methods.
• out: It is an object for a system class to execute the method.
• println: This is a method to print string which can be given within the double coats.
After printed the contents the cursor should be positioned at beginning of next line
• print: after printed the content the cursor should be positioned next to the printed content.

Java Tokens
A token in Java is a sequence of characters that represents a single element of a program. They are also
known as the fundamental building blocks of the program. Tokens can be classified as follows:

1. Keywords
2. Identifiers
3. Constants/Literals
4. Operators
5. Separators

1. Keyword
Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to perform
a specific function in a program. Since keywords are referred names for a compiler, they can’t be used as
variable names because by doing so, we are trying to assign a new meaning to the keyword which is not
allowed.
There are a total of 53 keywords in Java.

keyword Descriptions
byte A data type that can store whole numbers from -128 and 127

Declares a variable. New in Java 10


var

int A data type that can store whole numbers from -2147483648 to 2147483647
float A data type that can store fractional numbers from 3.4e−038 to 3.4e+038

double A data type that can store fractional numbers from 1.7e−308 to 1.7e+308

Char A data type that is used to store a single character

else Used in conditional statements

if Makes a conditional statement

while Used together with while to create a do-while loop

do Used together with while to create a do-while loop

Char A data type that is used to store a single character

Boolean A data type that can only store true or false values

A non-access modifier used for classes, attributes and methods, which makes
final
them non-changeable (impossible to inherit or override)

class Defines a class

break Breaks out of a loop or a switch block

2. Identifiers

Identifiers are used as the general terminology for naming of variables, functions and arrays. These are user-
defined names consisting of an arbitrarily long sequence of letters and digits with either a letter or the
underscore (_) as a first character. Identifier names must differ in spelling and case from any keywords.
keywords cannot be used as identifiers; they are reserved for special use. Once declared, can use the identifier
in later program statements to refer to the associated value.

Rules For Naming Java Identifiers

There are certain rules for defining a valid Java identifier. These rules must be followed, otherwise, we get a
compile-time error. These rules are also valid for other languages like C, and C++.

• The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]),
‘$‘(dollar sign) and ‘_‘ (underscore). For example “geek@” is not a valid Java identifier as it contains
a ‘@’ a special character.

• Identifiers should not start with digits([0-9]). For example “123geeks” is not a valid Java identifier.

• Java identifiers are case-sensitive.

• There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15
letters only.

• Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid statement
as a while is a reserved word. There are 53 reserved words in Java.

Examples of Valid Identifiers:

MyVariable
MYVARIABLE
myvariable
x

_myvariable
$myvariable
sum_of_array
geeks123

Examples of Invalid Identifiers:


My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric characte

3. Constants/Literals

Constants are also like normal variables. But the only difference is, their values cannot be modified by the
program once they are defined. Constants refer to fixed values. They are also called as 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 Constants may belong to any of the data type.

Syntax:

final data_type variable_name;

4. Operators

Java provides many types of operators which can be used according to the need. They are classified based on
the functionality they provide. Some of the types are-

• Arithmetic Operators

• Unary Operators

• Assignment Operator

• Relational Operators

• Logical Operators

• Ternary Operator

• Bitwise Operators

• Shift Operators

• instance of operator

• Precedence and Associativity

5. Separators
Separators are used to separate different parts of the codes. It tells the compiler about completion of a
statement in the program. The most commonly and frequently used separator in java is semicolon (;).
The separators in Java is also known as punctuators. There are nine separators in

Java, are as follows:

• 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.


Example:
int variable; //here the semicolon (;) ends the declaration of the variable

Command Line Arguments


Command-line arguments in Java allow you to pass information to a program when it is executed. These
arguments are passed as strings and can be accessed in the main method through the String[] args parameter.

Here’s an example program demonstrating how to use command-line arguments in Java:

// CommandLineArgumentsExample.java

public class CommandLineArgumentsExample

public static void main(String[] args)

// Check if any arguments are passed

if (args.length == 0)

System.out.println("No command-line arguments provided!");

else

System.out.println("Command-line arguments are:");

// Loop through and print all arguments

for (int i = 0; i < args.length; i++)


{

System.out.println("Argument " + (i + 1) + ": " + args[i]);

How to Run the Program

1. Save the code in a file named CommandLineArgumentsExample.java.

2. Compile the program using:

• javac CommandLineArgumentsExample.java
3. Run the program with command-line arguments:
java CommandLineArgumentsExample arg1 arg2 arg3

Example Output
For the command:
java CommandLineArgumentsExample Hello World Java
The output will be:
Command-line arguments are:
Argument 1: Hello
Argument 2: World
Argument 3: Java
Explanation
• args.length: Returns the number of arguments passed.
• args[i]: Accesses the ith argument (starting from 0).
• If no arguments are provided, the program informs the user that no arguments were passed.
Java Programming Fundamentals

Data Types

Data types in Java are of different sizes and values that can be stored in the variable that is made as per
convenience and circumstances to cover up all test cases.

Java is statically typed and also a strongly typed language because, in Java, each type of data (such as integer,
character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and
all constants or variables defined for a given program must be described with one of the Java data types.

Java has two categories in which data types are segregated

1. Primitive Data Type: such as Boolean, char, int, short, byte, long, float, and double. The Boolean
with uppercase B is a wrapper class for the primitive data type Boolean in Java.

2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

// Java Program to demonstrate int data-type

import java.io.*;

class GFG

public static void main (String[] args)

// declaring two int variables

int a = 10;

int b = 20;

System.out.println( a + b );

Output

30
Primitive Data Types in Java

Primitive data are only single values and have no special capabilities. There are 8 primitive data types.
They are depicted below in tabular format below as follows:
Primitive Data Types
1. Boolean Data Type
The Boolean data type represents a logical value that can be either true or false. Conceptually, it represents a
single bit of information, but the actual size used by the virtual machine is implementation-dependent and
typically at least one byte (eight bits) in practice. Values of the Boolean type are not implicitly or explicitly
converted to any other type using casts. However, programmers can write conversion code if needed.

Syntax:

boolean booleanVar;

Example:

Boolean one = false;

2. Byte Data Type

The Byte data type is an 8-bit signed two’s complement integer. The Byte data type is useful for saving
memory in large arrays.

Syntax:

byte byteVar;

Example:

byte a = 10, byte b = -20 ;

3. Short Data Type

The short data type is a 16-bit signed two’s complement integer. Similar to byte, a short is used when
memory savings matter, especially in large arrays where space is constrained.

Syntax:

short shortVar;

short myNum = 5000;

System.out.println(myNum);

Example:

short s = 10000, short r = -5000 ;


4. int Data Type

The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial,
the int data type is the preferred data type when we create variables with a numeric value.

Syntax:

int intVar;

int myNum = 100000;

System.out.println(myNum);

5. long Data Type

The long data type is a 64-bit signed two’s complement integer. It is used when an int is not large enough to
hold a value, offering a much broader range.

Syntax:

long longVar;

long myNum = 15000000000L;

System.out.println(myNum);

6. Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of double) if you
need to save memory in large arrays of floating-point numbers. The size of the float data type is 4 bytes (32
bits).

Syntax:

float floatVar;

float myNum = 5.75f;

System.out.println(myNum);

7. Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data type
is generally the default choice. The size of the double data type is 8 bytes or 64 bits.

Syntax: double doubleVar;

double myNum = 19.99d;

System.out.println(myNum);
9. char Data Type

The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).

Syntax:

char charVar;

Non-Primitive (Reference) Data Types


The Non-Primitive (Reference) Data Types will contain a memory address of variable values because the
reference types won’t store the variable value directly in memory. They are strings, objects, arrays, etc.

1. Strings

Strings are defined as an array of characters. The difference between a character array and a string in
Java is, that the string is designed to hold a sequence of characters in a single variable whereas, a
character array is a collection of separate char-type entities. Unlike C/C++, Java strings are not
terminated with a null character.

a. Syntax: Declaring a string


b. <String_Type> <string_variable> = “<sequence_of_string>”;
2. Array

An Array is a group of like-typed variables that are referred to by a common name. Arrays in Java work
differently than they do in C/C++. The following are some important points about Java arrays.

• In Java, all arrays are dynamically allocated. (discussed below)

• Since arrays are objects in Java, we can find their length using member length. This is different from
C/C++ where we find length using size.

• A Java array variable can also be declared like other variables with [] after the data type.

• The variables in the array are ordered and each has an index beginning with 0.

• Java array can also be used as a static field, a local variable, or a method parameter.

• The size of an array must be specified by an int value and not long or short.

• The direct superclass of an array type is Object.

Interface

Like a class, an interface can have methods and variables, but the methods declared in an interface are by
default abstract (only method signature, no body).
• Interfaces specify what a class must do and not how. It is the blueprint of the class.

• An Interface is about capabilities like a Player may be an interface and any class implementing
Player must be able to (or must implement) move(). So it specifies a set of methods that the class has
to implement.

Variables & Constants


Variables
Variables are the containers for storing the data values or can also call it a memory location name for the data.
A variable is a container that holds data which can change during program execution.

Declaration Syntax:

dataType variableName = value; // e.g., int age = 25;


Declare Java Variables

1. datatype: In Java, a data type define the type of data that a variable can hold.
2. data_name: Name was given to the variable.
Every variable has a:
• Data Type – The kind of data that it can hold. For example, int, string, float, char, etc.
• Variable Name – To identify the variable uniquely within the scope.
• Value – The data assigned to the variable.
Types of Java Variables

1. Local Variables
• 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.
Example
// Java Program to show the use of local variables
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;

// This variable is local to this main method only


System.out.println("Local Variable: " + var);
}
}
Output :10
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.

• Scope of instance variables are throughout the class except the static contexts.

Example
// Java Program to show the use of
// Instance Variables
import java.io.*;

class GFG {
// Declared Instance Variable
public String geek;
public int i;
public Integer I;
public GFG()
{
// Default Constructor
// initializing Instance Variable
this.geek = "Shubham Jain";
}
// Main Method
public static void main(String[] args)
{
// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
System.out.println("Default value for int is "+ name.i);
// toString() called internally
System.out.println("Default value for Integer is "+ name.I);
}
}
Output:
Geek name is: Shubham Jain
Default value for int is 0
Default value for Integer is null
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.

Example:
// Java Program to show the use of
// Static variables
import java.io.*;

class GFG {
// Declared static variable
public static String geek = "Shubham Jain";
public static void main(String[] args)
{

// geek variable can be accessed without object


// creation Displaying O/P GFG.geek --> using the
// static variable
System.out.println("Geek Name is : " + GFG.geek);

// static int c = 0;
// above line, when uncommented,
// will throw an error as static variables cannot be
// declared locally.
}
}
Example to understand the types of variables in java
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}

}//end of class

Constants
A constant is a variable whose value cannot change after initialization. Constants in Java are declared using
the final keyword.
Declaration Syntax:
final dataType CONSTANT_NAME = value; // e.g., final int MAX_AGE = 100;
haracteristics of Constants:
• The value must be assigned at the time of declaration or in a constructor.
• By convention, constant names are written in uppercase with underscores separating words.
Example:
public class ConstantsExample {
// Declaring constants using `final`
public static final double PI = 3.14159; // Constant for Pi
public static final int MAX_AGE = 100; // Maximum age constant

public static void main(String[] args) {


// Using constants in a program
double radius = 5.0; // Radius of a circle
double area = PI * radius * radius; // Calculate area using the constant PI

System.out.println("The radius of the circle is: " + radius);


System.out.println("The area of the circle is: " + area);

// Printing another constant


System.out.println("The maximum age allowed is: " + MAX_AGE);
}
}
Output:
The radius of the circle is: 5.0
The area of the circle is: 78.53975
The maximum age allowed is: 100

Keywords in java
Java has a set of keywords that are reserved words that cannot be used as variables, methods, classes, or any
other identifiers:

Keyword Description

abstract A non-access modifier. Used for classes and methods: An abstract class
cannot be used to create objects (to access it, it must be inherited from
another class). An abstract method can only be used in an abstract class,
and it does not have a body. The body is provided by the subclass (inherited
from)

assert For debugging

boolean A data type that can only store true or false values

break Breaks out of a loop or a switch block

byte A data type that can store whole numbers from -128 and 127

case Marks a block of code in switch statements

catch Catches exceptions generated by try statements

char A data type that is used to store a single character

class Defines a class

continue Continues to the next iteration of a loop

const Defines a constant. Not in use - use final instead

default Specifies the default block of code in a switch statement

do Used together with while to create a do-while loop

double A data type that can store fractional numbers from 1.7e−308 to 1.7e+308

else Used in conditional statements


enum Declares an enumerated (unchangeable) type

exports Exports a package with a module. New in Java 9

extends Extends a class (indicates that a class is inherited from another class)

final A non-access modifier used for classes, attributes and methods, which
makes them non-changeable (impossible to inherit or override)

finally Used with exceptions, a block of code that will be executed no matter if there
is an exception or not

float A data type that can store fractional numbers from 3.4e−038 to 3.4e+038

for Create a for loop

goto Not in use, and has no function

if Makes a conditional statement

implements Implements an interface

import Used to import a package, class or interface

instanceof Checks whether an object is an instance of a specific class or an interface

int A data type that can store whole numbers from -2147483648 to
2147483647

interface Used to declare a special type of class that only contains abstract methods

long A data type that can store whole numbers from -9223372036854775808 to
9223372036854775808

module Declares a module. New in Java 9

native Specifies that a method is not implemented in the same Java source file (but
in another language)

new Creates new objects

package Declares a package

private An access modifier used for attributes, methods and constructors, making
them only accessible within the declared class

protected An access modifier used for attributes, methods and constructors, making
them accessible in the same package and subclasses

public An access modifier used for classes, attributes, methods and constructors,
making them accessible by any other class
requires Specifies required libraries inside a module. New in Java 9

return Finished the execution of a method, and can be used to return a value from
a method

short A data type that can store whole numbers from -32768 to 32767

static A non-access modifier used for methods and attributes. Static


methods/attributes can be accessed without creating an object of a class

strictfp Obsolete. Restrict the precision and rounding of floating point calculations

super Refers to superclass (parent) objects

switch Selects one of many code blocks to be executed

synchronized A non-access modifier, which specifies that methods can only be accessed by
one thread at a time

this Refers to the current object in a method or constructor

throw Creates a custom error

throws Indicates what exceptions may be thrown by a method

transient Used to ignore an attribute when serializing an object

try Creates a try...catch statement

var Declares a variable. New in Java 10

void Specifies that a method should not have a return value

volatile Indicates that an attribute is not cached thread-locally, and is always read
from the "main memory"

while Creates a while loop

Java Naming Convention


Java naming convention is a rule to follow as you decide what to name identifiers such as class, package,
variable, constant, method, etc.

But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by
several Java communities such as Sun Microsystems and Netscape.

All the classes, interfaces, packages, methods and fields of Java programming language are given according
to the Java naming convention.
Naming Conventions of the Different Identifiers

The following table shows the popular conventions used for the different identifiers.

Identifiers Type Naming Rules Examples

It should start with the uppercase


letter. public class Employee
It should be a noun such as Color, {
Class
Button, System, Thread, etc. //code snippet
Use appropriate words, instead of }
acronyms.

It should start with the uppercase


letter.
interface Printable
It should be an adjective such as
{
Interface Runnable, Remote,
//code snippet
ActionListener.
}
Use appropriate words, instead of
acronyms.

It should start with lowercase class Employee


letter. {
It should be a verb such as // method
main(), print(), println(). void draw()
Method
If the name contains multiple {
words, start it with a lowercase //code snippet
letter followed by an uppercase }
letter such as actionPerformed(). }

It should start with a lowercase


letter such as id, name.
It should not start with the special
characters like & (ampersand), $ class Employee
(dollar), _ (underscore). {
If the name contains multiple // variable
Variable
words, start it with the lowercase int id;
letter followed by an uppercase //code snippet
letter such as firstName, }
lastName.
Avoid using one-character
variables such as x, y, z.
It should be a lowercase letter //package
such as java, lang. package com.javatpoint;
If the name contains multiple class Employee
Package
words, it should be separated by {
dots (.) such as java.util, //code snippet
java.lang. }

class Employee
{
It should be in uppercase letters //constant
such as RED, YELLOW. static final int MIN_AGE = 18;
If the name contains multiple //code snippet
words, it should be separated by }
Constant
an underscore(_) such as
MAX_PRIORITY.
It may contain digits but not as
the first letter.

CamelCase in Java naming conventions

Java follows camel-case syntax for naming the class, interface, method, and variable.

If the name is combined with two words, the second word will start with uppercase letter always such as
actionPerformed(), firstName, ActionEvent, ActionListener, etc.

Typecasting in Java

Typecasting in Java is the process of converting one data type to another data type using the casting
operator. When a valueis assigned from one primitive data type to another type, this is known as type
casting. To enable the use of a variable in a specific manner, this method requires explicitly instructing the
Java compiler to treat a variable of one data type as a variable of another data type.

Syntax: <datatype> variableName = (<datatype>) value;


Types of Type Casting
There are two types of Type Casting in java:
• Widening Type Casting
• Narrow Type Casting
Widening Type Casting

A lower data type is transformed into a higher one by a process known as widening type casting. Implicit
type casting and casting down are some names for it. It occurs naturally. Since there is no chance of data
loss, it is secure. Widening Type casting occurs when:
• The target type must be larger than the source type.
• Both data types must be compatible with each other.

Syntax:
larger_data_type variable_name = smaller_data_type_variable;

EXAMPLES
// Java program to demonstrate Widening TypeCasting
import java.io.*;

class GFG {
public static void main(String[] args)
{
int i = 10;

// Wideing TypeCasting (Automatic Casting)


// from int to long
long l = i;

// Wideing TypeCasting (Automatic Casting)


// from int to double
double d = i;

System.out.println("Integer: " + i);


System.out.println("Long: " + l);
System.out.println("Double: " + d);
}
}
Output
Integer: 10
Long: 10
Double: 10.0

Narrow Type Casting

The process of downsizing a bigger data type into a smaller one is known as narrowing type casting. Casting
up or explicit type casting are other names for it. It doesn’t just happen by itself. If we don’t explicitly do that,
a compile-time error will occur. Narrowing type casting is unsafe because data loss might happen due to the
lower data type’s smaller range of permitted values. A cast operator assists in the process of explicit casting.

Syntax: smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;

// Java Program to demonstrate Narrow type casting


import java.io.*;

class GFG {
public static void main(String[] args)
{
double i = 100.245;

// Narrowing Type Casting


short j = (short)i;
int k = (int)i;

System.out.println("Original Value before Casting" + i);


System.out.println("After Type Casting to short " + j);
System.out.println("After Type Casting to int "+ k);
}
}

Output
Original Value before Casting100.245
After Type Casting to short 100
After Type Casting to int 100

Explicit Upcasting
Upcasting is the process of casting a subtype to a supertype in the inheritance tree’s upward direction. When
a sub-class object is referenced by a superclass reference variable, an automatic process is triggered without
any further effort.

Example:
/ Java Program to demonstrate Narrow type casting
import java.io.*;
class GFG {
public static void main(String[] args)
{
double i = 100.245;

// Narrowing Type Casting


short j = (short)i;
int k = (int)i;

System.out.println("Original Value before Casting" + i);


System.out.println("After Type Casting to short " + j);
System.out.println("After Type Casting to int " + k);
}
}

Types of Explicit Casting


Mainly there are two types of Explicit Casting:
• Explicit Upcasting
• Explicit Downcasting
Explicit Upcasting

Upcasting is the process of casting a subtype to a supertype in the inheritance tree’s upward direction. When
a sub-class object is referenced by a superclass reference variable, an automatic process is triggered without
any further effort.

Explicit Downcasting

When a subclass type refers to an object of the parent class, the process is referred to as downcasting. If it is
done manually, the compiler issues a runtime ClassCastException error. It can only be done by using the
instanceof operator. Only the downcast of an object that has already been upcast is possible.

Operators and Expressions


In programming, operators are the special symbol that tells the compiler to perform a special operation.
Java operators are special symbols that perform operations on variables or values. They can be classified
into several categories based on their functionality. These operators play a crucial role in performing
arithmetic, logical, relational, and bitwise operations etc.
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator

• Arithmetic Operators: Arithmetic operators are used to perform common mathematical


operations.
• Unary operators: Unary operators are used with only one operand. For example, ++ is a unary
operator that increases the value of a variable by 1.

• Assignment Operators: Assignment operators are used to assign values to variables.


• Relational Operators: Relational operators are used to check the relationship between two
operands.

• Logical Operators: Logical operators are used to determine the logic between variables or values.
• Ternary Operator : The ternary operator (conditional operator) is shorthand for the if-then-else
statement.
Syntax :- variable = Expression ? expression1 : expression2 ;
Here's how it works.
o If the Expression is true, expression1 is assigned to the variable.
o If the Expression is false, expression2 is assigned to the variable.

• Bitwise Operators :Bitwise operators in Java are used to perform operations on individual bits.

• Shift Operators: Shift Operators are used to shift the bits of a number left or right, thereby multiplying
or dividing the number by two, respectively.
o << (Left shift) – Shifts bits left, filling 0s (multiplies by a power of two).
o >> (Signed right shift) – Shifts bits right, filling 0s (divides by a power of two), with the leftmost bit
depending on the sign.
o >>> (Unsigned right shift) – Shifts bits right, filling 0s, with the leftmost bit always 0.

• instanceof operator: The instance of operator is used for type checking. It can be used to test if an
object is an instance of a class, a subclass, or an interface.

Expressions in java
Expression: An expression is a combination of operators, constants and variables. An expression may
consist of one or more operands, and zero or more operators to produce a value.
Types of Expression

• Constant expressions: Constant Expressions consists of only constant values. A constant value is
one that doesn’t change.
• Integral expressions: Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
• Integral expressions: Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
• Relational expressions: Relational Expressions yield results of type bool which takes a value true
or false.
• Logical expressions: Logical Expressions combine two or more relational expressions and
produces bool type results.
• Pointer expressions: Pointer Expressions produce address values.
• Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They are
basically used for testing or shifting bits.
Control Structures in java

Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides statements
that can be used to control the flow of Java code. Such statements are called control flow
statements.
Java provides three types of control flow statements.

1. Decision Making statements

o if statements

o switch statement

2. Loop statements

o do while loop

o while loop

o for loop

o for-each loop

3. Jump statements

o break statement

o continue statement

Decision-Making statements:-

As the name suggests, decision-making statements decide when and which statement to
execute. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided.

If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program

is diverted depending upon the specific condition. The condition of the If statement
gives a Boolean value, either true or false. In Java, there are four types of if-statements
1. Simple if statement

2. if-else statement

3. if-else-if ladder

4. Nested if-statement

1) Simple if statement:-

It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.

Syntax of if statement is given below.

if(condition) {

statement 1; //executes when condition is true

Example :

If statement program

public class Student

public static void main(String[] args)

int x =10;

int y = 12;

if(x+y>2)

System.out.println("x + y is greater than 20");

}
}

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block. The else block is executed if the condition of the if-block is
evaluated as false.

Syntax:

if(condition) {

statement 1; //executes when condition is true

Else {

statement 2; //executes when condition is false

Example:

If-else Statement

public class Student

public static void main(String[] args)

int x = 10;

int y = 12;

if(x+y<10)

System.out.println("x + y is less than 10");


}

else

System.out.println("x + y is greater than 10");}

• if-else-if ladder:-

The if-else-if statement contains the if-statement followed by multiple else-if statements.

In other words, we can say that it is the chain of if-else statements that create a decision

tree where the program may enter in the block of code where the condition is true.

Syntax of if-else-if statement is given below.

if(condition 1) {

statement 1; //executes when condition 1 is true

else if(condition 2)

statement 2; //executes when condition 2 is true

else {

statement 2; //executes when all the conditions are false

Example:

If -else- if ladder
public class Student

public static void main(String[] args)

String city ="Delhi";

if(city == "Meerut")

System.out.println("city is meerut");

else if (city == "Noida")

System.out.println("city is noida");

else if(city == "Agra")

System.out.println("city is agra");

else

System.out.println(city);

• Nested if-statement:

In nested if-statements, the if statement can contain a if or if-else statement inside another
if or else-if statement.

Syntax of Nested if-statement is given below.

if(condition 1) {

statement 1; //executes when condition 1 is true

if(condition 2) {

statement 2; //executes when condition 2 is true

else{

statement 2; //executes when condition 2 is false

Example 1: nested if statemet

public class Test

public static void main(String args[])

int x = 30;

int y = 10;

if( x == 30 )

if( y == 10 )

System.out.print("X = 30 and Y = 10");

}
}

Example 2:- Nested if -else statement

public class Test

public static void main(String args[]) {

int x = 30;

int y = 10;

if( x < 30 )

System.out.print("X < 30");

else

if( y > 9 )

System.out.print("X > 30 and Y > 9");

Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement

contains multiple blocks of code called cases and a single case is executed based on
the variable which is being switched. The switch statement is easier to use instead of

if-else-if statements. It also enhances the readability of the program.

The syntax to use the switch statement is given below.

switch(expression)

case value1:

// Statements

break; // break is optional


case value2:

// Statements

break; // break is optional

....

....

....

default :

// default Statement

Example: -

public class SwitchExample

public static void main(String[] args)

//Declaring a variable for switch expression

int number=20;

//Switch expression

switch(number)

//Case statements

case 10: System.out.println("10");

break;

case 20: System.out.println("20");

break;
case 30: System.out.println("30");

break;

//Default case statement

default: System.out.println("Not in 10, 20 or 30");

Loop Statements:

In programming, sometimes we need to execute the block of code repeatedly while


some condition evaluates to true. However, loop statements are used to execute the set
of instructions in a repeated order. The execution of the set of instructions depends
upon a particular condition. In Java, we have three types of loops that execute
similarly. However, there are differences in their syntax and condition checking time.

1. for loop

2. while loop

3. do-while loop

1. for loop:

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable,
check the condition, and increment/decrement in a single line of code. We use the for
loop only when we exactly know the number of times, we want to execute the block of
code.

Syntax:-

for(initialization, condition, increment/decrement) {

//block of statements

}
Example

// Java program to demonstrates the working of for loop

import java.io.*;

class Geeks {

public static void main(String[] args)

for (int i = 0; i <= 10; i++) {

System.out.print(i + " ");

Output

0 1 2 3 4 5 6 7 8 9 10

2. for-each loop:

Java provides an enhanced for loop to traverse the data structures like array or collection.

In the for-each loop, we don't need to update the loop variable. This loop is used to iterate
over arrays or collections.
Syntax:

for (dataType variable : arrayOrCollection) {

// code to be executed

Example

// Java program to demonstrates the working of for each loop

import java.io.*;

class Geeks {

public static void main(String[] args)

int[] arr = { 1, 2, 3, 4, 5 };

for (int i : arr) {

System.out.print(i + " ");

Output

12345

3. while Loop

A while loop is used when we want to check the condition before running the code.

Syntax:

while (condition) {

// code to be executed
}

Example

// Java program to demonstrates

// the working of while loop

import java.io.*;

class Geeks {

public static void main(String[] args)

int i = 0;

while (i <= 10) {

System.out.print(i + " ");

i++;

}
Output

0 1 2 3 4 5 6 7 8 9 10
4. do-while Loop

The do-while loop in Java ensures that the code block executes at least once before the
condition is checked.

Syntax:

do {

// code to be executed

} while (condition);

Example
// Java program to demonstrates
// the working of do-while loop
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int i = 0;
do {
System.out.print(i + " ");
i++;
} while (i <= 10);
}
}

Output
0 1 2 3 4 5 6 7 8 9 10

Jump Statements in Java


Jumping statements are control statements that transfer execution control from one point to
another point in the program. There are three Jump statements that are provided in the Java
programming language:

1. Break statement.

2. Continue statement.

3. Return Statement.

Break statement: Break Statement to exit a loop:

In java, the break statement is used to terminate the execution of the nearest looping statement or
switch statement. The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.
Syntax:

break;

Example

// Java program to illustrate the

// break keyword in Java

import java.io.*;

class GFG {

public static void main(String[] args)

{
int n = 10;

for (int i = 0; i < n; i++) {

if (i == 6)

break;

System.out.println(i);

Output

Continue Statement

The continue statement pushes the next repetition of the loop to take place, hopping any code
between itself and the conditional expression that controls the loop.

Example:

// Java program to illustrate the

// continue keyword in Java

import java.io.*;
class GFG {

public static void main(String[] args)

for (int i = 0; i < 10; i++) {

if (i == 6) {

System.out.println();

// using continue keyword

// to skip the current iteration

continue;

System.out.println(i);

Output

5
7

Return Statement

The “return” keyword can help you transfer control from one method to the method that
called it. Since the control jumps from one part of the program to another, the return is also a
jump statement.

• “return” is a reserved keyword means we can’t use it as an identifier.

• It is used to exit from a method, with or without a value.

Example:

import java.io.*;
class ReturnExample {
// A simple method that takes two integers as input and
// returns their sum
public static int calculateSum(int num1, int num2)
{
// Print a message indicating the method has started
System.out.println("Calculating the sum of " + num1
+ " and " + num2);
int sum = num1 + num2;
System.out.println("The sum is: " + sum);
// Return the calculated sum
return sum;
// Note: Any code after the 'return' statement will
// not be executed. But "Final" is an exception in
// the case of try-catch-final block.
// System.out.println("end"); // error : unreachable
// statement
}
public static void main(String[] args)
{
// Call the calculateSum method
int result = calculateSum(5, 10);

// Print the result


System.out.println("Result: " + result);
}
}
Output
Calculating the sum of 5 and 10
The sum is: 15
Result: 15

You might also like