Java Notes UNIT-1
Java Notes UNIT-1
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.
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.
• 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.
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.
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.
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.
• 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.
• 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 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.
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.
“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
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.
Basis
SL.No C C++ Java
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:
• A compiler (javac),
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.
• 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,
• 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
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.
PC (program counter) register contains the address of the Java virtual machine instruction currently being
executed.
7) Execution Engine
It contains
1. A virtual processor
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.
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.
• 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:
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:
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:
int id;
double percentage;
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:
Example:
//statements
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
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
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)
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.
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.
• 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.
MyVariable
MYVARIABLE
myvariable
x
_myvariable
$myvariable
sum_of_array
geeks123
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:
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
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
• 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.
• Semicolon (;): It is the symbol that can be found at end of the statements. It
• Period (.): It separates the package name form the sub-packages and class. It also
// CommandLineArgumentsExample.java
if (args.length == 0)
else
• 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.
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.
import java.io.*;
class GFG
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:
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:
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;
System.out.println(myNum);
Example:
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;
System.out.println(myNum);
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;
System.out.println(myNum);
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;
System.out.println(myNum);
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.
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;
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.
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.
• 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.
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.
Declaration Syntax:
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;
• 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)
{
// 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
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)
boolean A data type that can only store true or false values
byte A data type that can store whole numbers from -128 and 127
double A data type that can store fractional numbers from 1.7e−308 to 1.7e+308
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
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
native Specifies that a method is not implemented in the same Java source file (but
in another language)
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
strictfp Obsolete. Restrict the precision and rounding of floating point calculations
synchronized A non-access modifier, which specifies that methods can only be accessed by
one thread at a time
volatile Indicates that an attribute is not cached thread-locally, and is always read
from the "main memory"
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.
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.
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.
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;
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.
class GFG {
public static void main(String[] args)
{
double i = 100.245;
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;
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.
• 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.
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.
if(condition) {
Example :
If statement program
int x =10;
int y = 12;
if(x+y>2)
}
}
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) {
Else {
Example:
If-else Statement
int x = 10;
int y = 12;
if(x+y<10)
else
• 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.
if(condition 1) {
else if(condition 2)
else {
Example:
If -else- if ladder
public class Student
if(city == "Meerut")
System.out.println("city is meerut");
System.out.println("city is noida");
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.
if(condition 1) {
if(condition 2) {
else{
int x = 30;
int y = 10;
if( x == 30 )
if( y == 10 )
}
}
int x = 30;
int y = 10;
if( x < 30 )
else
if( 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
switch(expression)
case value1:
// Statements
// Statements
....
....
....
default :
// default Statement
Example: -
int number=20;
//Switch expression
switch(number)
//Case statements
break;
break;
case 30: System.out.println("30");
break;
Loop Statements:
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:-
//block of statements
}
Example
import java.io.*;
class Geeks {
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:
// code to be executed
Example
import java.io.*;
class Geeks {
int[] arr = { 1, 2, 3, 4, 5 };
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
import java.io.*;
class Geeks {
int i = 0;
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
1. Break statement.
2. Continue statement.
3. Return Statement.
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
import java.io.*;
class GFG {
{
int n = 10;
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:
import java.io.*;
class GFG {
if (i == 6) {
System.out.println();
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.
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);