0% found this document useful (0 votes)
3 views79 pages

Unit 01 JAVA FUNDAMENTALS

The document outlines the fundamentals of Java programming, covering topics such as data types, variables, control statements, class fundamentals, and methods. It explains the structure of a Java program, the Java environment, and the execution process, as well as the characteristics and advantages of Java as a programming language. Additionally, it compares Java with C++ and discusses the pros and cons of using Java for software development.

Uploaded by

24443.cs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views79 pages

Unit 01 JAVA FUNDAMENTALS

The document outlines the fundamentals of Java programming, covering topics such as data types, variables, control statements, class fundamentals, and methods. It explains the structure of a Java program, the Java environment, and the execution process, as well as the characteristics and advantages of Java as a programming language. Additionally, it compares Java with C++ and discusses the pros and cons of using Java for software development.

Uploaded by

24443.cs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 79

22CS202 Java Programming

UNIT I

JAVA FUNDAMENTALS

An Overview of Java - Data Types, Variables, and Arrays – Operators - Control Statements –
Class Fundamentals – Declaring objects – Methods – Constructors – this keyword -
Overloading methods - Overloading constructors - Access Control – Static – Final.

1.1 An Overview of Java 2


Data Types, Variables, and
1.2
Arrays
1.2. 1
Data types
1 6
1.2. 1
Variables
2 8
1.2. 2
Identifiers
3 0
1.2. 2
Type Conversion and Casting
4 1
2
1.3 Operators
1
1.3. 2
Operator Precedence
1 7
1.3. 2
Java Expressions
2 8
2
1.4 Control Structures
9
4
1.5 I/O statements in Java
6
4
1.6 Java Naming Convention
8
5
1.7 Arrays
0
5
1.8 Access Modifiers
6
5
1.9 Class in Java
7
5
1.10 Object
8
6
1.11 Methods
2
6
1.12 Constructors
5
6
1.13 Constructor Overloading
8
6
1.14 Method Overloading in Java
9
7
1.15 this keyword in Java
2

R.M.K. College of Engineering and Technology 1


22CS202 Java Programming

7
1.16 Static Keyword
3
7
1.17 Final Keyword
5
7
Java Reserved Keywords
7

1.1 An Overview of Java

What is a Program?
 A program is a set of instructions that a computer uses to perform a specific function.
 A program is a collection of instructions that performs a specific task when executed
by a computer.
 A program must be written in a programming language.

Definition of Java:
• Java is simple yet powerful, general purpose, Object Oriented, platform
independent, high level programming language.

Java is used for:


 Mobile applications (especially Android apps)
 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

Why use Java?


 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
 It is one of the most popular programming languages in the world
 It has a large demand in the current job market
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast, and powerful
 It has a huge community support (tens of millions of developers)
 Java is an object-oriented language which gives a clear structure to programs and
allows code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or
vice versa

Editions of Java
 Java Standard Edition (Java SE)
o For building core java applications.
 Java Enterprise Edition (Java EE)
o For building distributed java applications.
 Java Micro Edition (Java ME)
o Developed to easily create mobile and embedded device applications.
 JavaFX (Java special EFF-ECTS)

R.M.K. College of Engineering and Technology 2


22CS202 Java Programming

o Uses a simple API to enable the development of rich online applications.

Java SE is a Java Development Kit (JDK) that comprises of:


 JRE: Java Runtime Environment. It is basically the Java Virtual Machine where
your Java programs run on. It also includes browser plugins for Applet execution.
 JDK: Software Development Kit, it is the full featured Software Development Kit
for Java, including JRE, and the compilers and tools (like JavaDoc, and Java
Debugger) to create and compile programs.

Java Environment / Java Architecture

Java programs can typically be developed in five stages:


1. Edit: Use an editor to type the source code (Welcome java)
2. Compile: javac, the Java compiler is used to translate the source code to machine
independent, bytecode. Bytecodes are called class file
3. Loading: Class loader loads the bytecodes from class and other libraries file into
main memory
4. Verify: Verifier make sure, whether the bytecodes are valid and do not violate security
restrictions

R.M.K. College of Engineering and Technology 3


22CS202 Java Programming

5. Execute: Java Virtual Machine uses a combination of interpretation and just in time
compilation to translate bytecodes into machine language. Applications are run on
user's machine, i.e., executed by interpreter with java command (java Welcome).

• Java Byte Code (*.class)


• Platform independent code generated by javac
• Class Loader
• Loads all the class files needed for execution
• Bytecode Verifier
• Checks code fragment for illegal code
• Java Interpreter
• Converts bytecode instruction to machine code
• Just In Time Compiler
• Compiles reusable byte code to machine code
• Runtime System
• Assists in the overall execution of the program

Structure of Java Program

1. Documentation Section
 It is used to improve the readability of the program.
 It consists of comments in Java which include basic information such as the method’s
usage or functionality to make it easier for the programmer to understand it while
reviewing or debugging the code.
 A Java comment is not necessarily limited to a confined space, it can appear anywhere
in the code.
 The compiler ignores these comments during the time of execution and is solely
meant for improving the readability of the Java program.
There are three types of comments that Java supp orts
• Single line Comment: Single line comments can be written using
// Single line Comment
• Multi line Comment: Block comments are used to provide descriptions of files,
methods, data structures and algorithms. Block comments may be used at the
beginning of each file and before each method
R.M.K. College of Engineering and Technology 4
22CS202 Java Programming

/*
Here is a block comment
*/
• Documentation Comment: The JDK javadoc tool uses doc comments when
preparing automatically generated documentation.
/**
documentation comments
*/

2. Package Statement
 Java that allows you to declare your classes in a collection called package.
 There can be only one package statement in a Java program and it must be at the
beginning of the code before any class or interface declaration.
 This statement is optional, for example, look at the statement below
package student;

3. Import Statement
 Many predefined classes are stored in packages in Java, an import statement is used to
refer to the classes stored in other packages.
 An import statement is always written after the package statement but it must be
before any class declaration, we can import a specific class or classes in an import
statement.

import.java.util.Date; //Imports the Date class from util package


import.java.sql.*; //Imports all the classes from sql package

4. Interface Section
 This section is used to specify an interface in Java.
 It is an optional section which is mainly used to implement multiple inheritance in
Java.
 An interface is a lot like a class in Java but it contains only constants and method
declarations.

5. Class Definition
 A Java program may contain several class definitions, classes are an essential part of
any Java program.
 It defines the information about the user defined classes in a program.
 A class is a collection of variables and methods that operate on the fields.
 Every program in Java will have at least one class with the main method.

6. Main Method Class


 The main method is from where the execution starts and follows the order specified
for the following statements.

Structure of main method class:


public class Example{
//main method declaration
public static void main(String args []) {
System.out.println("hello world”);
}

R.M.K. College of Engineering and Technology 5


22CS202 Java Programming

public class Example


 This creates a class called Example.
 You should make sure that the class name starts with a capital letter, and the public
word means it is accessible from any other classes
Braces
 The curly brackets are used to group all the commands together.
 To make sure that the commands belong to a class or a method

public static void main


 When the main method is declared public, it means that it can be used outside of this
class as well.
 The word static means that we want to access a method without making its objects.
 As we call the main method without creating any objects.
 The word void indicates that it does not return any value.
 The main is declared as void because it does not return any value.
 Main is the method, which is an essential part of any Java program

String[] args
 It is an array where each element is a string, which is named as args.
 If you run the Java code through a console, you can pass the input parameter.
 The main() takes it as an input.

System.out.println()
 The statement is used to print the output on the screen where the system is a
predefined class, out is an object of the PrintWriter class.
 The method println prints the text on the screen with a new line.
 All Java statements end with a semicolon.

Example Structure of Java Source File


/* A first program in Java */
public class Welcome
{
public static void main(String args[])
{
System.out.println(“Welcome to Java!”); // Prints Welcome to Java!
}
}

Using Blocks of Code


 Java allows two or more statements to be grouped into blocks of code, also called
code blocks.
 This is done by enclosing the statements between opening and closing curly braces.
 Once a block of code has been created, it becomes a logical unit that can be used any
place that a single statement can.

if(x<y){ //begin of block


x=y;
y=0;

R.M.K. College of Engineering and Technology 6


22CS202 Java Programming

} //end of block

Execution of Java Program


Java program can be executed using the following means
1. In command prompt
2. IDE
3. Online compilers

Command Prompt Execution


1. Download and Install JDK
(Refer: https://www.oracle.com/java/technologies/javase-downloads.html )
Installed in C:\Program Files\Java\JDK
2. Save the Source Code in any working space
Let Working Space be: D:\My Java Programs\Week1
3. Set the Path in Command Prompt
D:\My Java Programs\Week1> set path = “C:\Program Files\Java\JDK\Bin”
4. Compile the Source Code
D:\My Java Programs\Week1> javac Welcome.java
On successful Compilation: Welcome.class (Byte Code) is created
5. Interpret / Execute the Class File (Byte Code)
D:\My Java Programs\Week1> java Welcome

IDE Execution
Many Integrated Development Environment (IDE) are available, that helps in development
and execution of Java applications For E.g., Eclipse, JCreator, CodeBlocks, etc.
Refer: https://www.youtube.com/watch?v=jGAb70JyEQI
1. Download and Install IDE(Netbeans) and JDK (Refer:
https://www.eclipse.org/downloads/)
2. Open a new Java Project using the IDE.
3. Open a new class.
4. Add main method.
5. Compile and run using menus.

Online Compilers
Many online compilers are available for practicing Java program, which are simple to use.
1. https://www.onlinegdb.com/online_java_compiler
2. https://www.tutorialspoint.com/compile_java_online.php
3. https://compiler.javatpoint.com/opr/online java_compiler.jsp
4. https://www.jdoodle.com/online java compiler/
5. https://www.codechef.com/ide

Characteristics or Features of Java Programming Language


 Java is easy to write and more readable and eye-catching.
 Java has a concise, cohesive set of features that makes it easy to
Simple learn and use.
 Most of the concepts are drawn from C++ thus making Java
learning simpler.
Secure  Java programs cannot harm another system thus making it
secure.
 Java provides a secure means of creating Internet applications.

R.M.K. College of Engineering and Technology 7


22CS202 Java Programming

 Java provides a secure way to access web applications.


 Java programs can execute in any environment for which there
is a Java run-time system. (JVM)
 Java programs can be run on any platform (Linux, Windows,
Portable
Mac)
 Java programs can be transferred over the world wide web
(e.g., applets)
 Java programming is an object-oriented programming
language.
Object-oriented  Like C++ java provides most of the object-oriented features.
 Java is a pure OOP Language. (While C++ is semi-object-
oriented)
 Java encourages error-free programming by being strictly typed
Robust
and performing run-time checks.
 Java provides integrated support for multithreaded
Multithreaded
programming.
 Java is not tied to a specific machine or operating system
Architecture-
architecture.
neutral
 Machine Independent i.e., Java is independent of hardware.
 Java supports cross-platform code using Java bytecode.
Interpreted
 Bytecode can be interpreted on any platform by JVM.
High  Bytecodes are highly optimized.
performance  JVM can execute them much faster.
 Java was designed with a distributed environment.
Distributed
 Java can transmit, and run over the internet.
 Java programs carry with them substantial amounts of run-time
Dynamic type information that is used to verify and resolve accesses to
objects at run time.

C++ vs Java
Comparison
C++ Java
Index
Platform- C++ is platform- Java is platform-independent.
independent dependent.
Mainly used C++ is mainly used for Java is mainly used for application
for system programming. programming.
Goto C++ supports Java does not support the goto statement.
the goto statement.
Multiple C++ supports multiple Java does not support multiple inheritance
inheritance inheritance. through class. It can be achieved by
using interfaces in java.
Operator C++ supports operator Java does not support operator
Overloading overloading. overloading.
Pointers C++ supports pointers. Java supports pointer internally.

Compiler and C++ uses compiler only. Java uses both compiler and interpreter.
Interpreter
Call by Value C++ supports both call by Java supports call by value only. There is
and Call by value and call by no call by reference in java.

R.M.K. College of Engineering and Technology 8


22CS202 Java Programming

reference reference.
Structure and C++ supports structures Java does not support structures and
Union and unions. unions.
Thread C++ does not have built-in Java has built-in thread support.
Support support for threads.
Pros and Cons of Java programming.

Pros of Java programming:


1. Platform independence: Java programs can run on any platform with a Java Virtual
Machine (JVM), making it highly portable.
2. Object-oriented programming (OOP): Java is designed around the OOP paradigm,
allowing for modular and reusable code, easier maintenance, and improved code
organization.
3. Robust and secure: Java has built-in features for memory management, exception
handling, and automatic garbage collection, making it more robust and less prone to
errors. It also has a strong security model with features like bytecode verification and
sandboxing.
4. Large community and extensive libraries: Java have a vast community of
developers and a rich ecosystem of libraries, frameworks, and tools that make
development faster and more efficient.
5. Multithreading support: Java provides built-in support for multithreading, allowing
for concurrent programming and efficient utilization of system resources.
6. Scalability: Java's scalability is well-suited for developing large-scale applications. It
can handle high loads and supports distributed computing through technologies like
Java EE and cloud platforms.
7. Strong performance: While Java may not be as fast as some low-level languages, it
has a just-in-time (JIT) compiler that optimizes performance at runtime, and its
performance is generally considered satisfactory for most applications.

Cons of Java programming:


1. Verbosity: Java code can be verbose compared to some other programming
languages. It often requires more lines of code to accomplish a task, which can slow
down development time.
2. Slower startup time: Java applications typically have a longer startup time due to the
JVM initialization process and class loading. This can be a drawback for certain types
of applications that require near-instantaneous response times.
3. Memory consumption: Java's automatic memory management comes with a cost.
The JVM's memory footprint can be larger compared to languages with manual
memory management, although this gap has been reduced in recent versions.
4. Limited low-level programming: Java is not well-suited for low-level programming
tasks or accessing hardware directly. It is primarily used for application development
and may not be the best choice for system-level programming.
5. Lack of backward compatibility: While Java strives for backward compatibility,
new versions may introduce changes that can break compatibility with older code.
This can require updates and adjustments to existing applications when migrating to
newer Java versions.
6. Less suitable for mobile development: Although Java has been traditionally used for
Android app development, newer frameworks like Kotlin have gained popularity due
to their more concise syntax and better interoperability with existing Java codebases.

R.M.K. College of Engineering and Technology 9


22CS202 Java Programming

7. Licensing concerns: While Java itself is open-source, some third-party libraries and
frameworks used in Java development may have different licensing requirements that
developers need to be aware of.

Java Language Fundamentals


1. Keywords
2. Data Types
3. Variables
4. Operators
5. Conditional Statements
6. Loops

Java Tokens
In Java programming, tokens are the smallest individual units of a program. They are the
building blocks of the language and are categorized into several types. The different types of
Java tokens in detail:
1. Keywords: Keywords are reserved words in Java that have predefined meanings and
cannot be used as identifiers (variable names, class names, etc.). Some examples of
keywords in Java include class, public, static, void, if, else, while, and return.
2. Identifiers: Identifiers are used to name classes, variables, methods, and other
program entities. They are user-defined and follow certain rules. An identifier must
start with a letter, underscore (_), or dollar sign ($), and can be followed by letters,
digits, underscores, or dollar signs.
3. Literals: Literals represent constant values in a program. They can be of various
types:
a. Integer literals: Examples include 0, 10, and -5. They represent whole
numbers.
b. Floating-point literals: Examples include 3.14, 1.0, and -2.5. They represent
decimal numbers.
c. Character literals: Represented within single quotes (''), such as 'a', '1', or '\n'.
They represent individual characters.
d. String literals: Represented within double quotes (""), such as "Hello", "Java",
or "42". They represent a sequence of characters.
e. Boolean literals: The two Boolean literals are true and false. They represent
logical values.
4. Operators: Java includes various operators for performing different operations.
Examples of operators include arithmetic operators (+, -, *, /, %), assignment
operators (=, +=, -=, *=, /=), comparison operators (==, !=, <, >, <=, >=), logical
operators (&&, ||, !), and more.
5. Separators: Separators are used to separate different parts of a Java program.
Common separators include parentheses (), curly braces {}, square brackets [],
comma,, semicolon ;, period ., and colon :.
6. Comments: Comments are used to add explanatory notes within the code. They are
ignored by the compiler and are not executed. Java supports two types of comments:
a. Single-line comments: Denoted by //. Anything written after // on the same
line is considered a comment.
b. Multi-line comments: Denoted by /* at the beginning and */ at the end.
Anything between these symbols is treated as a comment, even if it spans
multiple lines.

R.M.K. College of Engineering and Technology 10


22CS202 Java Programming

7. Whitespace: Whitespace refers to spaces, tabs, and newlines that separate tokens in a
program. It is used for formatting and readability purposes. Whitespace is generally
ignored by the Java compiler.

Keywords

 A Java keyword is one of 50 reserved terms that have a special function and a set
definition in the Java programming language.
 The fact that the terms are reserved means that they cannot be used as identifiers for
any other program elements, including classes, subclasses, variables, methods,
and objects.
abstract continue for new switch
*** *
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** Instance return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
*
const float native super while

Object Oriented Programming


 Object Oriented Programming is a paradigm (pattern) that provides many concepts
such as class, object, data abstraction, encapsulation, inheritance, polymorphism, etc.
 Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
 Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects.
 It simplifies software development and maintenance by providing some concepts:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Object

R.M.K. College of Engineering and Technology 11


22CS202 Java Programming

 Any entity that has state and behaviour is known as an object.


 For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
 An Object can be defined as an instance of a class.
 An object contains an address and takes up some space in memory.

Class
 Collection of objects is called class. It is a logical entity.
 A class can also be defined as a blueprint from which you can create an individual
object.
 Class does not consume any space.
 Class declaration is required to define a valid Java class file.

Inheritance

R.M.K. College of Engineering and Technology 12


22CS202 Java Programming

 When one object acquires all the properties and behaviours of a parent object, it is
known as inheritance.
 It provides code reusability.
 It is used to achieve runtime polymorphism.

Polymorphism

 If one task is performed in different ways, it is known as polymorphism.


 For example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.
 In Java, we use method overloading and method overriding to achieve polymorphism.

Abstraction
 Hiding internal details and showing functionality is known as abstraction.
 In the abstraction concept, we do not show the actual implementation to the end user,
instead we provide only essential things.
 For example, phone call, we do not know the internal processing.
 In Java, we use abstract class and interface to achieve abstraction.

R.M.K. College of Engineering and Technology 13


22CS202 Java Programming

Encapsulation
 Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
 For example, a capsule, it is wrapped with different medicines.
 A java class is the example of encapsulation.

Characteristics of Object-Oriented Programming


A class represents the set of fields or methods that are common to all
Class objects under a single name. A class is a blueprint or prototype for
objects. It is used to create user-defined data types.
An object is an instance (single occurrence) of a class. An entity that a
Object has state and behaviour is known as an object. An object is a real-world
entity. An object is a run-time entity.
Abstraction is the process of hiding certain details and only showing the
Abstraction essential features of the object. In other words, it deals with the outside
view of an object (interface).
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.
Encapsulation is a protective shield that prevents the data from being

R.M.K. College of Engineering and Technology 14


22CS202 Java Programming

accessed by the code outside this shield.


Inheritance is the mechanism in java by which one class is allowed to
inherit the features (fields and methods) of another class.
Super Class: The class whose features are inherited is known as a
superclass (or a base class or a parent class)
Inheritance
Sub Class: The class that inherits the other class is known as a subclass
(or a derived class, extended class, or child class). The subclass can add
its own fields and methods in addition to the superclass fields and
methods.
Polymorphism is the ability of an object to take on many forms.
Polymorphism in java is a concept by which a single action can be
performed in different ways. The most common use of polymorphism in
OOP occurs when a parent class reference is used to refer to a child class
Polymorphis object.
m There are two types of polymorphism in java:
1. Compile time polymorphism
2. Runtime polymorphism or Dynamic Method Despatch.
Polymorphism in java can be performed by method overloading and
method overriding.

First Java Program


class Welcome
{
public static void main(String[] args)
{
System.out.println("Hello World! Welcome to Java Programming!");
}
}

Output: Hello World! Welcome to Java Programming!

Execution Flow

1.2 Data Types, Variables, and Arrays

R.M.K. College of Engineering and Technology 15


22CS202 Java Programming

1.2.1 Data types


 Data types specify the different sizes and values that can be stored in the variable.
 There are two types of data types in Java:
1. Primitive data types: It holds the value of the data item. The primitive data
types include Boolean, char, byte, short, int, long, float, and double.
2. Non-primitive data types: It holds the memory address where the data item
(object) is stored. It is also known as Reference datatypes. The non-primitive
data types include Classes, Interfaces, and Arrays.

What is primitive and non-primitive data type in Java?


 Primitive types are predefined (already defined) in Java and is named by a reserved
keyword.
 Non-primitive types are created by the programmer and is not defined by Java (except
for String).
 Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.

Primitive Vs Non-Primitive Data Types


Primitive Data Type Non-primitive Data Type
These are built-in data types These are created by the users
Does not support additional methods Support additional methods
Always has a value It can be null
Starts with lower-case letter Starts with upper-case letter
Size depends on the data type Same size for all
Java Primitive Data Types
 In Java language, primitive data types are the building blocks of data manipulation.
 These are the most basic data types available in Java language.

There are 8 types of primitive data types:


Data Type Default Value Default size Example
Boolean false 1 bit True, False
byte 0 1 byte (none)
char '\u0000' 2 bytes ‘a’, ‘\u0041’, ‘\101’, ‘\\’. ‘\’, ‘\n’
short 0 2 bytes (none)
int 0 4 bytes -2, -1, 0, 1, 2
long 0L 8 bytes -2L, -1L, 0L, 1L, 2L
float 0.0f 4 bytes 1.23e100f, -1.23e-100f, .3f, 3.14f
double 0.0d 8 bytes 1.23456e300d, -1.23456e-300d, 1e1d

R.M.K. College of Engineering and Technology 16


22CS202 Java Programming

Boolean Data Type


 The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.
 The Boolean data type specifies one bit of information, but its "size" cannot be
defined precisely.
Example: Boolean one = false;

Valid range of values, operators, and operations for Boolean variables.


Value true or false
Typical true, false
literals
Operations and, or, not
Operators && , | | , !

Byte Data Type


 The byte data type is an example of a primitive data type.
 It is an 8-bit signed two's complement integer.
 Its value range lies between -128 to 127 (inclusive).
 Its default value is 0.
 The byte data type is used to save memory in large arrays where memory savings is
most required.
 It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of the "int" data type.
Example: byte a = 10, byte b = -20;

Short Data Type


 The short data type is a 16-bit signed two's complement integer.
 Its value range lies between -32,768 to 32,767 (inclusive).
 Its default value is 0.
 The short data type can also be used to save memory just like the byte data type.
 A short data type is 2 times smaller than an integer.
Example: short s = 10000, short r = -5000;

Int Data Type

R.M.K. College of Engineering and Technology 17


22CS202 Java Programming

 The int data type is a 32-bit signed two's complement integer.


 Its value range lies between - 2,147,483,648 (-231) to 2,147,483,647 (231-1) (inclusive).
 Its default value is 0.
 The int data type is generally used as a default data type for integral values unless
there is no problem with memory.
Example: int a = 100000, int b = -200000;

Long Data Type


 The long data type is a 64-bit two's complement integer.
 Its value-range lies between -9,223,372,036,854,775,808(-263) to
63 -1
9,223,372,036,854,775,807(2 ) (inclusive).
 Its default value is 0.
 The long data type is used when you need a range of values more than those provided
by int.
Example: long a = 100000L, long b = -200000L;

Float Data Type


 The float data type is a single-precision 32-bit IEEE 754 floating point.
 Its value range is unlimited.
 It is recommended to use a float (instead of a double) if you need to save memory in
large arrays of floating-point numbers.
 The float data type should never be used for precise values, such as currency.
 Its default value is 0.0F.
Example: float f1 = 234.5f;

Double Data Type


 The double data type is a double-precision 64-bit IEEE 754 floating point.
 Its value range is unlimited.
 The double data type is generally used for decimal values just like float.
 The double data type also should never be used for precise values, such as currency.
 Its default value is 0.0d.
Example: double d1 = 12.3;

Char Data Type


 The char data type is a single 16-bit Unicode character.
 Its value range lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).
 The char data type is used to store characters.
Example: char letterA = 'A';

1.2.2 Variables
 Java is a statically typed programming language. It means, all variables must be
declared before its use. Java is also a strictly typed language.
 A variable is a container that holds the value while the Java program is executed.
 A variable is assigned with a data type.
 Variable is a name of a memory location.
 There are three types of variables in java: local, instance, and static.

Variable declaration

R.M.K. College of Engineering and Technology 18


22CS202 Java Programming

In Java we can have three different scopes of variables:


1) Local Variable
 A variable declared inside the body of the method is called local variable.
 Local variable can be used only within that method and the other methods in
the class are not even aware that the variable exists.
 A local variable cannot be defined with "static" keyword.
2) Static Variable
 A variable that is declared with a keyword “static” is called a static variable.
 It cannot be local, initialized only once, at the start of the program execution.
 A single copy of the static variable be created and it can be shared among all
the instances of the class.
 Memory allocation for static variables happens only once when the class is
loaded in the memory.
3) Instance Variable
 Instance variables are variables declared within a class but outside any method
without static keyword. These variables are initialized when the class is
instantiated.
 Instance variables can be accessed from inside any method, constructor, or
blocks of that class.
4) Final Variable
 A final variable is a variable that declared using final keyword.
 The final variable is initialized only once, and does not allow any method to
change its value again.
 The variable created using final keyword acts as constant.
 All variables like local, instance, and static variables can be final variables.
5) Variable marked as volatile
 If a variable is marked as volatile, every time the variable is used it must be
read from the main memory.
 Similarly, every time a variable is written, the value must be stored in main
memory.
class SharedObj
{
static volatile int sharedVar = 6;
}

Field / Variable declarations are composed of three components, in order:

R.M.K. College of Engineering and Technology 19


22CS202 Java Programming

1. Zero or more modifiers, such as public or private.


2. The field's type.
3. The field's name.

Types:
 All variables must have a type.
 Primitive types such as int, float, boolean, etc. Or you can use reference types, such as
strings, arrays, or objects.

Rules to declare a Variable:


• Variable names are case sensitive
• A variable name can consist of capital letters (A-Z), lowercase letters (a-z), digits (0-
9), and two special characters such as underscore (_) and dollar sign ($).
• Subsequent characters may be letters, digits, dollar signs, or underscore characters
• White space is not permitted
• keyword or reserved word should not be used as variable names
• If the name chosen consists of only one word, spell that word in all lowercase letters.
• If it consists of more than one word, capitalize the first letter of each subsequent word
Example: gearRatio and currentGear
• If variable stores a constant value, such as static final int NUM_GEARS 6 the
convention changes slightly, capitalizing every letter and separating subsequent words
with the underscore character

Example:
public class VariableDemo {
int data = 50; // instance variable
// static variable
static final int MAXIMUM_DATA = 100;
void method() {
int currentData = 90; // local variable
}
}// end of class

Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
//Demonstrate dynamic initialization
class DynInit{
public static void main(String[] args){
double a=3.0, b=4.0;
//c is dynamically initialized
double c = Math.sqrt( a*a + b*b);
System.out.println("Hypotenuse is" +c);
}
}
Here, three local variables a, b, and c are declared. The first two, a and b, are initialized by
constants. However, c is initialized dynamically to the length of the hypotenuse.

Example to understand the types of variables in java


public class A

R.M.K. College of Engineering and Technology 20


22CS202 Java Programming

{
int data=50; //instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
System.out.println(n);
}
public static void main(String args[])
{
A a=new A();
System.out.println(a.data);
System.out.println(m);
a.method();
}
}//end of class

1.2.3 Identifiers
 All Java variables must be identified with unique names. These unique names are
called identifiers.
 Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
 It is recommended to use descriptive names to create understandable and maintainable
code:

Example
int minutesPerHour = 60;
int m = 60;

The general rules for naming variables are:


• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter
• Names should start with a lowercase letter and it cannot contain whitespace
• Names can also begin with $ and _ (but we will not use it in this tutorial)
• Names are case sensitive ("myVar" and "myvar" are different variables)
• Reserved words (like Java keywords, such as int or boolean) cannot be used as names.

1.2.4 Type Conversion and Casting


While assigning a value of one type to a variable of another type. If the two types are
compatible, then Java will perform the conversion automatically. Automatic type conversion
will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.

Assign an int value to a byte variable. A byte is smaller than an int. This kind of conversion is
sometimes called a narrowing conversion. Remainder of the number division 256 will be
stored as byte.

A cast is simply an explicit type conversion. It has this general form:


(target-type) value;
R.M.K. College of Engineering and Technology 21
22CS202 Java Programming

When a floating-point value is assigned to an integer type, the conversion is called as


truncation.

Type Promotion: One operand in expression is float entire expression is promoted as float. If
one operand is long, whole expression is promoted to long.

1.3 Operators
 Operators are the symbols used to perform specific operations.
 Various operators can be used for different purposes.

The operators are categorized as:


1. Arithmetic operators
2. Logical operators
3. Unary operators
4. Assignment operators
5. Ternary operator
6. Relational operators
7. Bitwise operators
8. Shift operators
9. instanceOf operator

1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.

Operator Description
+ Additive operator (also used for string concatenation)
- Subtractive operator
* Multiplication operator
/ Division operator
% Modulus operator

Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10;
int numTwo = 5;
System.out.println(numOne + numTwo); //Output will be 15
System.out.println(numOne - numTwo); //Output will be 5
System.out.println(numOne * numTwo); //Output will be 50
System.out.println(numOne / numTwo); //Output will be 2
System.out.println(numOne % numTwo); //Output will be 0
}
}

2. Logical Operators

R.M.K. College of Engineering and Technology 22


22CS202 Java Programming

Logical operators are used to combine two or more relational expressions or to negate the
result of a relational expression.

Operator Name Description


&& AND The result will be true only if both expressions are true
|| OR The result will be true if any one of the expressions is true
! NOT The result will be false if the expression is true and vice versa

Assume A and B to be two relational expressions. The below tables show the result
for various logical operators based on the value of expressions, A and B.

A B A&&B A||B AAAA A !A


True True True True True False
True Fals False True Fals True
e e
False True False True
False Fals False False
e

3. Unary Operators
Unary operators act upon only one operand and perform operations such as increment,
decrement, negating an expression, or inverting a Boolean value.

Operator Name Description


Post increment Increments the value after use
++
Pre increment Increments the value before use
Post increment decrements the value after use
--
Pre increment decrements the value before use
~ Bitwise complement Flips bits of the value
! Logical negation Inverts the value of a Boolean

Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10;
int numTwo = 5;
boolean isTrue = true;
System.out.println(numOne++ + " " + ++numOne); //Output will be 10 12
System.out.println(numTwo-- + " " + --numTwo); //Output will be 5 3
System.out.println(!isTrue + " " + ~numOne); //Output will be false -13
}
}
4. Assignment Operator
The assignment operator is used to assign the value on the right-hand side to the variable on
the left-hand side of the operator. Some of the assignment operators are given below:
Operato
Description
r

R.M.K. College of Engineering and Technology 23


22CS202 Java Programming

= Assigns the value on the right to the variable on the left


Adds the current value of the variable on the left to the value on the right and
+=
then assigns the result to the variable on the left
Subtracts the value of the variable on the right from the current value of the
-=
variable on left and then assigns the result to the variable on the left
Multiplies the current value of the variable on left to the value on the right and
*=
then assigns the result to the variable on the left
Divides the current value of the variable on left by the value on the right and
/=
then assign the result to the variable on the left

Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10; //The value 10 is assigned to numOne
System.out.println(numOne); //Output will be 10
numOne += 5;
System.out.println(numOne); //Output will be 15
numOne -= 5;
System.out.println(numOne); //Output will be 10
numOne *= 5;
System.out.println(numOne); //Output will be 50
numOne /= 5;
System.out.println(numOne); //Output will be 10
}
}

5. Ternary Operator
The ternary operator is used as a single-line replacement for if-then-else statements and acts
upon three operands.

Syntax:
<condition> ? <value if condition is true> : < value if condition is false>

Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10;
int numTwo = 5;
int min = (numOne < numTwo) ? numOne : numTwo;
System.out.println(min); //Output will be 5
}
}

Here, first the condition (numOne < numTwo) is evaluated. The result is false and hence, min
will be assigned the value numTwo.

R.M.K. College of Engineering and Technology 24


22CS202 Java Programming

6. Relational operators
 Relational operators are used to compare two values.
 The result of all the relational operations is either true or false.

Operato Description
r
== Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to

Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10;
int numTwo = 5;
System.out.println(numOne > numTwo); //Output will be true
}
}

7. Bitwise Operators
 Bitwise operators are used to perform manipulation of individual bits of a number.

Let us understand how to convert a decimal number to a binary number and vice versa. The
decimal or the base 10 number system is used in everyday life but the binary number system
is the basis for representing data in computing systems.

2 25
2 1 1
2
2 6 0
2 3 0
2 1 1
0 1

25 decimal = 11001 binary

Steps to convert a decimal number to a binary number.


Step 1: Divide the decimal number by 2.
Step 2: Write the number on the right-hand side. This will be either 1 or 0
Step 3: Divide the result of the division again by 2 and write the remainder.
Step 4: Continue this process until the result of the division is 0.
Step 5: The first remainder that you received is the least significant bit and the last remainder
is the most significant bit.

Steps to convert the binary number back to a decimal number.


R.M.K. College of Engineering and Technology 25
22CS202 Java Programming

The decimal number is equal to the sum of binary digits (dn) times their power of 2 (2n).

Let us take the example of 11001.


11001 = 1*24+1*23+0*22+0*21+1*20 = 16+8+0+0+1 = 25

24 = 16 23 = 8 22 = 4 21 = 2 20 = 1
1 1 0 0 1
16 + 8 + 0 + 0 + 1 = 25

Bitwise OR (|)
 It returns bit by bit OR of the input values.
 If either of the bits is 1, then it gives 1, else it gives 0.

E.g. - The output of 10 | 5 is 15.

Bitwise AND (&)


 It returns bit by bit AND of the input values.
 If both the bits are 1, then it gives 1, else it gives 0.

E.g. - The output of 10 & 5 is 0.

Left shift operator (<<)


 It takes two operators and left shifts the bits of the first operand.
 The second operand decides the number of places to shift.
 It fills 0 on voids left as a result.

E.g. - The output of 10<<1 is 20 if the numbers are stored in a 32-bit system.

10 is represented as 00000000 00000000 00000000 00001010.

After left shifting by 1 bit, the result becomes 00000000 00000000 00000000 000010100
which is 20.

The 0 that is highlighted is present because of the void.

Similarly, the output of 10<<2 is 40.

R.M.K. College of Engineering and Technology 26


22CS202 Java Programming

Signed Right shift operator (>>)


 It takes two operators and right shifts the bits of the first operand.
 The second operand decides the number of places to shift.
 It fills 0 on voids left because of the first operand being positive else it fills 1.

E.g. – An example of the positive number

The output of 10>>1 is 5.


10 is represented as 00000000 00000000 00000000 00001010.

After right shifting by 1 bit, the result becomes 00000000 00000000 00000000 00000101
which is 5.
Example of a negative number

The output of -10>>1 is -5.


-10 is represented as 11111111 11111111 11111111 11110110.

After right shifting by 1 bit, the result becomes 11111111 11111111 11111111 11111011 which
is -5.

Unsigned Right shift operator (>>>)


 It takes two operators and right shifts the bits of the first operand.
 The second operand decides the number of places to shift.
 It fills 0 on voids left as a result.
E.g. – An example a of a positive number

The output of 10>>>1 is 5.


10 is represented as 00000000 00000000 00000000 00001010.

After right shifting by 1 bit, the result becomes 00000000 00000000 00000000 00000101
which is 5.
Example of a negative number

The output of -10>>>1 is 214783643.


-10 is represented as 11111111 11111111 11111111 11110110.

After right shifting by 1 bit, the result becomes 01111111 11111111 11111111 11111011 which
is 214783643.

8. Shift Operators
Java Shift Operators are also a part of bitwise operators. There are the following types of shift
operators.
 Left Shift - Shifts the bits of the number two places to the left and fills the voids with
0’s.
 Right Shift - Shifts the bits of the number two places to the right and fills the voids
with 0’s The sign of the number decides the value of the left bit.
 Unsigned Right Shift - It is also the same as the right shift however it changes the
leftmost digit’s value to 0.

9. instanceOf Operator

R.M.K. College of Engineering and Technology 27


22CS202 Java Programming

 This is a type-check operator.


 It checks whether a particular object is the instance of a certain class or not.
 It returns true if the object is a member of the class and false if not.

1.3.1 Operator Precedence


 The operator precedence represents how two expressions are bound together.
 In an expression, it determines the grouping of operators with operands and decides
how an expression will evaluate.
 While solving an expression two things must be kept in mind the first is a
precedence and the second is associativity.

Precedence Operator Type Associativity


() Parentheses Left to Right
1 [] Array subscript
· Member selection
++ Unary post-increment Right to left
2
-- Unary post-decrement
++ Unary pre-increment Right to left
-- Unary pre-decrement
+ Unary plus
3 - Unary minus
! Unary logical negation
~ Unary bitwise complement
(type) Unary type cast
* Multiplication Left to right
4 / Division
% Modulus
+ Addition Left to right
5
- Subtraction
<< Bitwise left shift Left to right
6 >> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension
< Relational less than Left to right
<= Relational less than or equal
7 > Relational greater than
>= Relational greater than or equal
instanceOf Type comparison (objects only)
== Relational is equal to Left to right
8
!= Relational is not equal t o
9 & Bitwise AND Left to right
10 ^ Bitwise exclusive OR Left to right
11 | Bitwise inclusive OR Left to right
12 && Logical AND Left to right
13 || Logical OR Left to right
14 ?: Ternary conditional Right to left
15 = Assignment Right to left
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment

R.M.K. College of Engineering and Technology 28


22CS202 Java Programming

/= Division assignment
%= Modulus assignment

Advantages of Operators
1. Expressiveness: Operators in Java provide a concise and readable way to perform
complex calculations and logical operations.
2. Time-Saving: Operators in Java save time by reducing the amount of code required
to perform certain tasks.
3. Improved Performance: Using operators can improve performance because they are
often implemented at the hardware level, making them faster than equivalent Java
code.

Disadvantages of Operators
1. Operator Precedence: Operators in Java have a defined precedence, which can lead
to unexpected results if not used properly.
2. Type Coercion: Java performs implicit type conversions when using operators, which
can lead to unexpected results or errors if not used properly.
3. Overloading: Java allows for operator overloading, which can lead to confusion and
errors if different classes define the same operator with different behavior.

1.3.2 Java Expressions


 An expression is a collection of operators and operands that represents a specific
value.
 In the above definition, an operator is a symbol that performs tasks like arithmetic
operations, logical operations, and conditional operations, etc.
 Operands are the values on which the operators perform the task. Here operand can be
a direct value or variable or address of memory location.

Expression Types
 Infix Expression
o The expression in which the operator is used between operands is called infix
expression.

 Postfix Expression
o The expression in which the operator is used after operands is called postfix
expression.

 Prefix Expression
o The expression in which the operator is used before operands is called a prefix
expression.

R.M.K. College of Engineering and Technology 29


22CS202 Java Programming

1.4 Control Structures


 In a program, the instructions are usually executed line by line. Sometimes, all the
statements in a program may not be executed.
 There can be changes in the flow of control and can be implemented using control
structures.

Conditional or Selection Statement


 Conditional statements in Java are the executable block of code (or branch to a
specific code) dependent on certain conditions.
 These statements are also known as decision statements or selection statements in
Java.

if statement
 In java, we use the if statement to test a condition and decide the execution of a block
of statements based on that condition result.
 The if statement checks, the given condition then decides the execution of a block of
statements.
 If the condition is True, then the block of statements is executed and if it is False, then
the block of statements is ignored.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}

Example
public class Main
{
public static void main(String[] args)
{
int x = 20;
int y = 18;
if (x > y)
{
System.out.println("x is greater than y"); // Output : x is greater than y
}

R.M.K. College of Engineering and Technology 30


22CS202 Java Programming

}
}

Flow of execution

if-else statement
 In java, we use the if-else statement to test a condition and pick the execution of a
block of statements out of two blocks based on that condition result.
 The if-else statement checks the given condition then decides which block of
statements to be executed based on the condition result.
 If the condition is True, then the true block of statements is executed and if it is False,
then the false block of statements is executed.

Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}

Example 1 – Greatest of two numbers


import java.util.*;
class Main
{
public static void main(String args[])
{
int num1,num2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Two Numbers:");
num1=sc.nextInt();
num2=sc.nextInt();
if(num1>num2)
{

R.M.K. College of Engineering and Technology 31


22CS202 Java Programming

System.out.println("The First Number is Greater than the Second Number.");


}
else
{
System.out.println("The Second Number is Greater than the First Number.");
}
}
}

Output
Enter the Two Numbers:
10 12

The Second Number is Greater than the First Number.

Flow of execution

Example 2 – Odd or even number


public class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}

R.M.K. College of Engineering and Technology 32


22CS202 Java Programming

if...else if Statement
 To evaluate more than one conditions at the same time, you can use else if statement
in Java.
 Multi selection enables the developer to determine the actions that must be
accomplished in certain conditions by imposing a requisite.
 We can combine an else and an if to make an else if and test a whole range of
mutually exclusive possibilities.

Syntax
if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is true
}
else
{
// block of code to be executed if the condition1 is false and condition2 is false
}

Example 1 – Grade System


public class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{

R.M.K. College of Engineering and Technology 33


22CS202 Java Programming

System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}

Output: C grade

Example 2 – positive, negative, or zero

public class PositiveNegativeExample


{
public static void main(String[] args)
{
int number=-13;
if(number>0)
{
System.out.println("POSITIVE");
}
else if(number<0)
{
System.out.println("NEGATIVE");
}
else
{
System.out.println("ZERO");
}
}
}

Nested if statement
 The nested if statement represents the if block within another if block.
 Here, the inner if block condition executes only when the outer if block condition is
true.

Syntax

if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}

Example

R.M.K. College of Engineering and Technology 34


22CS202 Java Programming

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number: ");
int num=sc.nextInt();
if( num < 100 )
{
System.out.println("The entered number is less than 100");
if(num > 50)
{
System.out.println("The entered number is greater than 50");
}
}
else
{
System.out.println("The entered number is greater than 100");
}
}
}

Output
Enter a number: 67
The entered number is less than 100
The entered number is greater than 50

switch statement
 Using the switch statement, one can select only one option from a greater number of
options very easily.
 In the switch statement, we provide a value that is to be compared with a value
associated with each option.
 Whenever the given value matches the value associated with an option, the execution
starts from that option.
 In the switch statement, every option is defined as a case.

Syntax

switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;

R.M.K. College of Engineering and Technology 35


22CS202 Java Programming

Flow of execution

Example
public class Main
{
public static void main(String[] args)
{
int day = 4;
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:

R.M.K. College of Engineering and Technology 36


22CS202 Java Programming

System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}

Output: Thursday

Loop or Iteration Statement


 Iterative statements are used to execute a statement or a block of statements
repeatedly if the given condition is true.
 The iterative statements are also known as looping statements or repetitive statements.
There are three types of loops in Java.
 for loop
 for each loop
 while loop
 do...while loop

for statement
 The for statement is used to execute a single statement or a block of statements
repeatedly if the given condition is TRUE.

Syntax
for(initialization; condition; increment/decrement)
{
//statement or code to be executed
}
A simple for loop is the same as C/C++. We can initialize the variable, and check the
condition and increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition that is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is
an optional condition.
2. Condition: It is the second condition that is executed each time to test the condition
of the loop. It continues execution until the condition is false. It must return a Boolean
value of either true or false. It is an optional condition.
3. Increment/Decrement: Increments or decrements the variable value. It is an optional
condition.
4. Statement: The statement of the loop is executed each time until the second condition
is false.

Example 1: Program to find the sum of natural numbers from 1 to 1000.


class Main
{
public static void main(String[] args)

R.M.K. College of Engineering and Technology 37


22CS202 Java Programming

{
int sum = 0;
int n = 1000;
// for loop
for (int i = 1; i <= n; ++i)
{
// body inside for loop
sum += i; // sum = sum + i
}
System.out.println("Sum = " + sum);
}
}

Output: Sum = 500500

Example 2: Program to find the factorial of a number


class FactorialExample
{
public static void main(String args[])
{
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++)
{
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}

Output: Factorial of 5 is: 120

Example 3: Program to find the sum of digits of a number


import java.util.Scanner;
class Scaler
{
public static void main(String arg[])
{
long n, sumOfDigits;
// creating object of scanner class
Scanner scn = new Scanner(System.in);
System.out.println("Enter a number: ");
n = scn.nextLong(); // taking input
for(sumOfDigits = 0 ; n!=0 ; n/=10)
{
sumOfDigits += n%10; // adding remainder (last digit) to the sum
}
System.out.println(sumOfDigits); // printing result
}

R.M.K. College of Engineering and Technology 38


22CS202 Java Programming

Output

Enter a number: 23
5
Flow of execution

for-each statement
 The Java for-each statement was introduced since Java 5.0 version.
 It provides an approach to traverse through an array or collection in Java.
 The for-each statement also known as enhanced for statement.
 The for-each statement executes the block of statements for each element of the given
array or collection.

Syntax
for(datatype variablename : Array)
{
//block of statement
}
statement after for

Example
public class ForEachTest {
public static void main(String[] args) {
int[] arrayList = {10, 20, 30, 40, 50};
for(int i : arrayList) {
System.out.println("i = " + i);
}
System.out.println("Statement after for-each!");
}
}

R.M.K. College of Engineering and Technology 39


22CS202 Java Programming

Flow of execution

while statement
 The while statement is used to execute a single statement or block of statements
repeatedly if the given condition is TRUE.
 The while statement is also known as Entry control looping statement.

Syntax:
while (condition)
{
//code to be executed
Increment/decrement statement
}

Example 1: Program to find whether a given number is Armstrong or not.


import java.util.Scanner;
public class Armstrong
{
public static void main(String[] args)
{
int number, originalNumber, remainder, result = 0;
Scanner sc=new Scanner(System.in);
number=sc.nextInt();
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
{
System.out.println(number + " is an Armstrong number.");
}
else
{

R.M.K. College of Engineering and Technology 40


22CS202 Java Programming

System.out.println(number + " is not an Armstrong number.");


}
}
}

Output: 371 is an Armstrong number.

Example 2: Program to print multiplication table


import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number: ");
int n=sc.nextInt(); //Declare and initialize the number
int i=1;
System.out.println("The multiplication table of "+n+" is: ");
//Infinite Loop Example
while(i<=10)
{
System.out.println(n+" * "+i+" = "+ (n*i));
i++;
}
}
}

Output
Enter the number: 3
The multiplication table of 3 is:
3*1=3
3*2=6
3*3=9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30

Flow of execution

R.M.K. College of Engineering and Technology 41


22CS202 Java Programming

do-while statement
 The do-while statement is used to execute a single statement or block of statements
repeatedly if given the condition is TRUE.
 The do-while statement is also known as the Exit control looping statement.

Syntax
do
{
//code to be executed / loop body
//update statement
}while (condition);

Example
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
Output
1
2
3
4
5
6
7
8
9

R.M.K. College of Engineering and Technology 42


22CS202 Java Programming

10

Flow of execution

do...while loop vs while


S. No. do..while while
1 do..while loop evaluates its condition while loop evaluates the condition at first
at the last of the loop instead of the
first
2 Therefore, the statements within the Therefore, the statements within the do
do block are always executed at least block are not executed if the condition is
once whether the condition is true or false
false

Flow Control or Jump Statement


 Jump statements that used to transfer execution control from one line to another line.

break statement
 The break statement in java is used to terminate a switch or looping statement.
 That means the break statement is used to come out of a switch statement and a
looping statement like while, do-while, for, and for-each.

Syntax
jump-statement;
break;
Example
public class BreakExample
{
public static void main(String[] args)
{
//using for loop
for(int i=1;i<=10;i++)
{
if(i==5)
{
//breaking the loop
R.M.K. College of Engineering and Technology 43
22CS202 Java Programming

break;
}
System.out.println(i);
}
}
}

Output

1
2
3
4

Flow of execution

continue statement
 The continue statement is used to move the execution control to the beginning of the
looping statement.
 When the continue statement is encountered in a looping statement, the execution
control skips the rest of the statements in the looping block and directly jumps to the
beginning of the loop.
 The continue statement can be used with looping statements like while, do-while, for,
and for-each.
 When we use continue statement with while and do-while statements, the execution
control directly jumps to the condition.

 When we use continue statement with for statement the execution control directly
jumps to the modification portion (increment/decrement/any modification) of the for
loop.

Syntax
jump-statement;
continue;

Flow of execution

R.M.K. College of Engineering and Technology 44


22CS202 Java Programming

Example
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}

Output
1
2
3
4
6
7
8
9
10

Labelled break and continue statement


 The java programming language does not support goto statement, alternatively, the
break and continue statements can be used with label.
 The labelled break statement terminates the block with specified label.
 The labelled continue statement takes the execution control to the beginning of a loop
with specified label.

Example

R.M.K. College of Engineering and Technology 45


22CS202 Java Programming

import java.util.Scanner;
public class JavaLabelledStatement {
public static void main(String args[]) {
Scanner read = new Scanner(System.in);
reading: for (int i = 1; i <= 3; i++) {
System.out.print("Enter an even number: ");
int value = read.nextInt();
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + i*10 + " out of 30.");
break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more options...");
continue reading;
}
}
}
}

return statement
 In java, the return statement used to terminate a method with or without a value.
 The return statement takes the execution control to the calling function.
 That means the return statement transfer the execution control from called function to
the calling function by carrying a value.
 In java, the return statement used with both methods with and without return type.
 In the case of a method with the return type, the return statement is mandatory, and it
is optional for a method without return type.
 When a return statement used with a return type, it carries a value of return type.
 But, when it is used without a return type, it does not carry any value.
 Instead, simply transfers the execution control.

Following are the important points must remember while returning a value:
1. The return type of the method and type of data returned at the end of the method
should be of the same type. For example, if a method is declared with the float return
type, the value returned should be of float type only.
2. The variable that stores the returned value after the method is called should be a
similar data type otherwise, the data might get lost.
3. If a method is declared with parameters, the sequence of the parameter must be the
same while declaration and method call.

Syntax:

The syntax of a return statement is the return keyword is followed by the value to be returned.
return returnvalue;

1.5 I/O statements in Java

 Java I/O (Input and Output) is used to process the input and produce the output.
 Java uses the concept of a stream to make I/O operations fast.

R.M.K. College of Engineering and Technology 46


22CS202 Java Programming

 The java.io package contains all the classes required for input and output operations.

Java Scanner Class


 Java Scanner class allows the user to take input from the console.
 It belongs to java.util package.
 It is used to read the input of primitive types like int, double, long, short, float, and
byte.
 It is the easiest way to read input in a Java program.

Syntax
Scanner object_name=new Scanner(System.in);
Example
Scanner s=new Scanner(System.in);

Methods of Java Scanner Class


Datatyp Method Description
e
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double nextDouble() It is used to scan the next token of the input as a double.
byte nextByte() It is used to scan the next token of the input as a byte.
String nextLine() Advances this scanner past the current line.

Example
import java.util.*;
public class ScannerClassExample1
{
public static void main(String args[])
{
String s = "Hello, This is JavaTpoint.";
Scanner scan = new Scanner(s);
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
}
}

Output
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23

R.M.K. College of Engineering and Technology 47


22CS202 Java Programming

Age: 23
Enter your salary: 25000
Salary: 25000.0

Java BufferedReader Class

 Java BufferedReader class is used to read the text from a character-based input
stream.
 It can be used to read data line by line by readLine() method.
 It makes the performance fast.
 It inherits Reader class.

Syntax
BufferedReader Object_name=new BufferedReader(new InputStreamReader(System.in));

Example
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Example
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String args[]) throws Exception
{
String s = "Hello, This is JavaTpoint.";
//Create scanner Object and pass string in it
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
System.out.println("--------Enter Your Details-------- ");
System.out.print("Enter your name: ");
String name = scan.readLine();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = Integer.parseInt(scan.readLine());
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = Double.parseDouble(scan.readLine());
System.out.println("Salary: " + d);
}
}

Output
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0

R.M.K. College of Engineering and Technology 48


22CS202 Java Programming

Output Statement
 In Java, System.out.println() is a statement that prints the argument passed to it.
 The println() method display results on the monitor.

Example
System.out.println(“Welcome to Java Output”);
System.out.println(“Welcome”+a);

1.6 Java Naming Convention


 Java naming convention is a rule to follow as you decide what to name your
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.
 If you fail to follow these conventions, it may generate confusion or erroneous code.

Advantage of Naming Conventions in Java


 By using standard Java naming conventions, you make your code easier to read for
yourself and other programmers.
 Readability of Java program is very important.
 It indicates that less time is spent to figure out what the code does.

Class
 It should start with the uppercase letter.
 It should be a noun such as Color, Button, System, Thread, etc.
 Use appropriate words, instead of acronyms.

public class Employee


{
//code snippet
}

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

Method
 It should start with lowercase letter.
 It should be a verb such as main(), print(), println().
 If the name contains multiple words, start it with a lowercase letter followed by an
uppercase letter such as actionPerformed().

class Employee

R.M.K. College of Engineering and Technology 49


22CS202 Java Programming

{
// method
void draw()
{
//code snippet
}
}

Variable
 It should start with a lowercase letter such as id, name.
 It should not start with the special characters like & (ampersand), $ (dollar), _
(underscore).
 If the name contains multiple words, start it with the lowercase letter followed by an
uppercase letter such as firstName, lastName.
 Avoid using one-character variables such as x, y, z.

class Employee
{
// variable
int id;
//code snippet
}

Package
 It should be a lowercase letter such as java, lang.
 If the name contains multiple words, it should be separated by dots (.) such as
java.util, java.lang.

//package
package employee;
class Employee
{
//code snippet
}

Constant
 It should be in uppercase letters such as RED, YELLOW.
 If the name contains multiple words, it should be separated by an underscore (_) such
as MAX_PRIORITY.
 It may contain digits but not as the first letter.

class Employee
{
//constant
static final int MIN_AGE = 18;
//code snippet
}

1.7 Arrays
 Java array is an object which contains elements of a similar data type.

R.M.K. College of Engineering and Technology 50


22CS202 Java Programming

 Additionally, the elements of an array are stored in a contiguous memory location.


 It is a data structure where we store similar elements.
 We can store only a fixed set of elements in a Java array.
 Array in Java is index-based, the first element of the array is stored at the 0 th index, 2nd
element is stored on the 1st Index, and so on.

Advantages
 Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
 Random access: We can get any data located at an index position.

Disadvantages
 Size Limit: We can store only the fixed size of elements in the array. It does not grow
its size at runtime. To solve this problem, a collection framework is used in Java
which grows automatically.

Types of Arrays in java


 One Dimensional Array
 Two-Dimensional Array

One Dimensional Array in Java

Syntax to Declare an Array in Java


dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];

Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
or
int intArray[] = new int[20]; // combining both statements in one

//Java Program to illustrate how to declare, instantiate, initialize, and traverse the
array.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization

R.M.K. College of Engineering and Technology 51


22CS202 Java Programming

a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Output
10
20
70
40
50

//Java program to find the sum of ‘n’ numbers


import java.util.Scanner;
class sum
{
public static void main(String arg[])
{
int n,sum=0;
Scanner sc=new Scanner(System.in);
System.out.println("enter how many numbers you want to sum:");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("enter the "+n+" numbers ");
for(int i=0;i<n;i++)
{
System.out.println("enter number "+(i+1)+":");
a[i]=sc.nextInt();
}
for(int i=0;i<n;i++)
{
sum+=a[i];
}
System.out.println("the sum of "+n+" numbers is ="+sum);
}
}

Output
enter how many numbers you want to sum: 5
enter the 5 numbers
enter number 1: 32
enter number 2: 12
enter number 3: 43
enter number 4: 212
enter number 5: 23

R.M.K. College of Engineering and Technology 52


22CS202 Java Programming

the sum of 5 numbers is =322

Two-Dimensional Array in Java


In such cases, data is stored in a row and column-based index (also known as matrix form).

Syntax
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][];

Example to instantiate Multidimensional Array in Java


int[][] arr=new int[3][3]; //3 row and 3 column

//Java program to add two matrices


import java.util.Scanner;
public class MatrixAdd
{
public static void main(String[] args)
{
int i, j;
int[][] a = new int[3][3];
int[][] b = new int[3][3];
int[][] c = new int[3][3];
Scanner s = new Scanner(System.in);
System.out.print("Enter 9 elements for first matrix: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
a[i][j] = s.nextInt();
}
}
System.out.print("Enter 9 elements for second matrix: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
b[i][j] = s.nextInt();
}
}
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
b
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("\n----Addition Result----");
for(i=0; i<3; i++)
{

R.M.K. College of Engineering and Technology 53


22CS202 Java Programming

for(j=0; j<3; j++)


{
System.out.print(c[i][j]+ " ");
}
System.out.print("\n");
}
}
}

Output
Enter 9 elements for first matrix:
1
2
3
4
5
6
7
8
9
Enter 9 elements for second matrix:
9
8
7
6
5
4
3
2
1

----Addition Result----
10 10 10
10 10 10
10 10 10

//Java program to multiply two matrices


import java.util.Scanner;
public class MatixMultiplication
{
public static void main(String args[])
{
int n;
Scanner input = new Scanner(System.in);
System.out.println("Enter the base of squared matrices");
n = input.nextInt();
int[][] a = new int[n][n];
int[][] b = new int[n][n];
int[][] c = new int[n][n];

R.M.K. College of Engineering and Technology 54


22CS202 Java Programming

System.out.println("Enter the elements of 1st matrix row wise \n");


for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = input.nextInt();
}
}
System.out.println("Enter the elements of 2nd matrix row wise \n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
b[i][j] = input.nextInt();
}
}
System.out.println("Multiplying the matrices...");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("The product is:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}

Output
Enter the base of squared matrices 2
Enter the elements of 1st matrix row wise
1
2
3
4
Enter the elements of 2nd matrix row wise

2
3

R.M.K. College of Engineering and Technology 55


22CS202 Java Programming

4
Multiplying the matrices...
The product is:
7 10
15 22

Exceptions in Array
 NullPointerException
o In java, an array created without size and initialized to null remains null only.
o It does not allow us to assign a value.
o When we try to assign a value, it generates a NullPointerException.

 ArrayIndexOutOfBoundsException
o In java, the JVM (Java Virtual Machine)
throws ArrayIndexOutOfBoundsException when an array is trying to access
with an index value of negative value, value equal to array size, or value more
than the array size.

Looping through an array


import java.util.Scanner;
public class ArrayExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int size, sum = 0;
System.out.print("Enter the size of the list: ");
size = read.nextInt();
short list[] = new short[size];
System.out.println("Enter any " + size + " numbers: ");
for(int i = 0; i < size; i++) // Simple for statement
list[i] = read.nextShort();
for(int i : list) // for-each statement
sum = sum + i;
System.out.println("Sum of all elements: " + sum);
}
}
1.8 Access Modifiers
 The access specifiers (also known as access modifiers) used to restrict the scope or
accessibility of a class, constructor, variable, method or data member of class and
interface.
 We divide modifiers into two groups:
o Access Modifiers - controls the access level
o Non-Access Modifiers - do not control access level, but provides other
functionality

Access Modifiers
Access Modifier Details
private Will be accessible within the class

R.M.K. College of Engineering and Technology 56


22CS202 Java Programming

default Will be accessible within the package


protected Will be visible to sub class and within the same package
public Will be accessible from anywhere

Non-Access Modifiers
Modifier Description
final Attributes and methods cannot be overridden / modified
static Attributes and methods belong to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods.
The method does not have a body. For example abstract void run(); The
body is provided by the subclass (inherited from)
transient Attributes and methods are skipped when serializing the object containing
them
synchronized Methods can only be accessed by one thread at a time
volatile The value of an attribute is not cached thread-locally, and is always read
from the main memory.

Example:
class ParentClass
{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData()
{
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass
{
void accessData()
{
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();

R.M.K. College of Engineering and Technology 57


22CS202 Java Programming

obj.showData();
obj.accessData();
}
}

Output
Inside ParentClass
a = 10
b = 20
c = 30
d = 40
Inside ChildClass
a = 10
b = 20
c = 30

1.9 Class in Java


 Java is an object-oriented programming language, so everything in java program must
be based on the object concept.
 In a java programming language, the class concept defines the skeleton of an object.
 The java class is a template of an object.
 The class defines the blueprint of an object.
 Every class in java forms a new data type.
 Once a class got created, we can generate as many objects as we want.
 Every class defines the properties and behaviors of an object.
 All the objects of a class have the same properties and behaviors that were defined in
the class.

Definition:
 Class is a detailed description, definition, and a logical template to
create objects that share common properties and methods.
 Class is a detailed description, definition, and the template of what
an object will be. It is the building bock that leads to object-
oriented programming.

Every class of java programming language has the following characteristics.


 Identity - It is the name given to the class.
 State - Represents data values that are associated with an object.
 Behavior - Represents actions can be performed by an object.

A class in Java can contain:


 Fields / Variable
 Methods
 Constructors
 Blocks
 Nested class and interface

Syntax to declare a class:


class <class_name>
{

R.M.K. College of Engineering and Technology 58


22CS202 Java Programming

field / variable;
method;
}

Example
class Sample
{
int a,b; //variable declaration
public:
void get(); //method1
void display(); //method2
}

1.10 Object
 An entity that has state, identity and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc.

Object Definitions
 An object is a real-world entity.
 An object is a runtime entity.
 The object is an entity which has state and behavior.
 The object is an instance of a class.

Definition:
 Object us a member of java class. Each object has an identity, a
behavior, and a state. State of an object is stored in fields
(variables), method (functions) displays the object behavior.

An object consists of:


1. State: It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior: It is represented by the methods of an object. It also reflects the response of
an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Creating an Object
 In java, an object is an instance of a class.
 When an object of a class is created, the class is said to be instantiated.
 All the objects that are created using a single class have the same properties and
methods.
 But the value of properties is different for every object.

Syntax
classname objectname=new classname();

Example for declaring object

Sample s=new Sample();

//Java Program to illustrate how to define a class and fields

R.M.K. College of Engineering and Technology 59


22CS202 Java Programming

//Defining a Student class.


class Student
{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}

3 Ways to initialize object


There are 3 ways to initialize object in Java.
• By reference variable
• By method
• By constructor

1) Object and Class Example: Initialization through reference


• Initializing an object means storing data into the object.

class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}

2) Object and Class Example: Initialization through method


• In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method.
• Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.

class Student
{

R.M.K. College of Engineering and Technology 60


22CS202 Java Programming

int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}

Anonymous object
• Anonymous simply means nameless.
• An object which has no reference is known as an anonymous object.
• It can be used at the time of object creation only.
• If you must use an object only once, an anonymous object is a good approach.
new Calculation();//anonymous object

Calling method through a reference:


Calculation c=new Calculation();
c.fact(5);
Calling method through an anonymous object
new Calculation().fact(5);

Example:
class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factorial is "+fact);
}

R.M.K. College of Engineering and Technology 61


22CS202 Java Programming

public static void main(String args[])


{
new Calculation().fact(5);//calling method with anonymous object
}
}

Output: Factorial is 120

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.

Initialization of primitive variables:


int a=10, b=20;

Initialization of reference variables:


Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects

Example:
//Java Program to illustrate the use of Rectangle class which has length and width data
members
class Rectangle
{
int length;
int width;
void insert(int l,int w)
{
length=l;
width=w;
}
void calculateArea()
{
System.out.println(length*width);
}
}
class TestRectangle2
{
public static void main(String args[])
{
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Output:
55
45

R.M.K. College of Engineering and Technology 62


22CS202 Java Programming

Difference Between Class and Object:


There are many differences between object and class. Some differences between object and
class are given below:
Class Object
Class is used as a template for declaring and An object is an instance of a class.
creating the objects.
When a class is created, no memory is Objects are allocated memory space
allocated. whenever they are created.
The class must be declared first and only An object is created many times as per
once. requirement.
A class cannot be manipulated as they are Objects can be manipulated.
not
available in the memory.
A class is a logical entity. An object is a physical entity.
It is declared with the class keyword It is created with a class name in C++
and
with the new keywords in Java.
Class does not contain any values which Each object has its own values, which are
can be associated with the field. associated with it.
A class is used to bind data as well as Objects are like a variable of the class.
methods together as a single unit.
Example: Bike Example: Ducati, Suzuki, Kawasaki

1.11 Methods
 A method is a block of statements under a name that gets executes only when it is
called.
 Every method is used to perform a specific task.
 The major advantage of methods is code re-usability (define the code once, and use it
many times).
 In a java programming language, a method defined as a behaviour of an object. That
means, every method in java must belong to a class.
 Every method in java must be declared inside a class.

Declaring Methods

Syntax
return_type method_name(argument_list)
{
//statements;
}

Every method declaration has the following characteristics.


 returnType - Specifies the data type of a return value.

R.M.K. College of Engineering and Technology 63


22CS202 Java Programming

 name - Specifies a unique name to identify it.


 parameters - The data values it may accept or recieve.
 { } - Defienes the block belongs to the method.

Methods in Java
• modifier − It defines the access type of the method and it is optional to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
• method body − The method body defines what the method does with the statements.

Creating a method
 A method is created inside the class and it may be created with any access specifier.
However, specifying access specifier is optional.

Syntax
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}

Rules:
 The methodName must begin with an alphabet, and the Lower-case letter is preferred.
 The methodName must follow all naming rules.
 If you do not want to pass parameters, we ignore it.
 If a method defined with return type other than void, it must contain the return
statement, otherwise, it may be ignored.

Calling a method
 In java, a method call precedes with the object name of the class to which it belongs
and a dot operator.
 It may call directly if the method defined with the static modifier.
 Every method call must be made, as to the method name with parentheses (), and it
must terminate with a semicolon.

Syntax
<objectName>.<methodName>( actualArguments );

 The method call must pass the values to parameters if it has.


 If the method has a return type, we must provide the receiver.

Rules
 The objectName must begin with an alphabet, and a Lower-case letter is preferred.
 The objectName must follow all naming rules.

R.M.K. College of Engineering and Technology 64


22CS202 Java Programming

Example
class Rectangle
{
int length;
int width;
void insert(int l, int w)
{
length=l;
width=w;
}
void calculateArea()
{
System.out.println(length*width);
}
}
class TestRectangle1
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Output
55
45

Variable arguments of a method


 In java, a method can be defined with a variable number of arguments.
 That means creating a method that receives any number of arguments of the same data
type.

Syntax
<returnType> <methodName>(dataType...parameterName);

Example
public class JavaMethodWithVariableArgs
{
void display(int...list)
{
System.out.println("\nNumber of arguments: " + list.length);
for(int i : list)
{
System.out.print(i + "\t");
}

R.M.K. College of Engineering and Technology 65


22CS202 Java Programming

}
public static void main(String[] args)
{
JavaMethodWithVariableArgs obj = new JavaMethodWithVariableArgs();
obj.display(1, 2);
obj.display(10, 20, 30, 40, 50);
}
}

Output
Number of arguments: 2
1 2
Number of arguments: 5
10 20 30 40 50

1.12 Constructors
• In Java, constructor is a block of codes like method.
• It is called when an instance of object is created and memory is allocated for the
object.
• It is a special type of method which is used to initialize an object.

 A constructor is a special method of a class that has the same name as the class
name.
 The constructor gets executes automatically on object creation.
 It does not require the explicit method call.
 A constructor may have parameters and access specifiers too.
 In java, if you do not provide any constructor the compiler automatically creates a
default constructor.

Rules for creating Java constructor


• Constructor name must be same as its class name
• Constructor must have no explicit return type
• Invoked Automatically
• Cannot be inherited
• Multiple constructors used in a class

When a constructor is called?


• Every time an object is created using new() keyword, atleast one constructor is
called.
• It is called a default constructor. It is called constructor because it constructs the
values at the time of object creation.
• It is not necessary to write a constructor for a class.
• It is because if class does not have any constructor, java compiler creates a default
constructor.

How Constructors are Different from Methods in Java?


• Constructors must have the same name as the class within which it is defined it is not
necessary for the method in Java.
• Constructors do not return any type while method(s) have the return type or void if
does not return any value.

R.M.K. College of Engineering and Technology 66


22CS202 Java Programming

• Constructors are called only once at the time of Object creation while method(s) can
be called any number of times.

Types of Java constructors


• No-argument constructor
• Default constructor
• Parameterized constructor

No-argument constructor
• A constructor that has no parameter is known as the No-argument or Zero argument
constructor.
• If we do not define a constructor in a class, then the compiler creates a constructor
(with no arguments) for the class.
• And if we write a constructor with arguments or no arguments then the compiler does
not create a default constructor.

class A{
A(){
System.out.println("Hi");
}
public static void main(String[] args){
A ob = new A();
}
}

Example:
package com.journaldev.constructor;

public class Data {


//no-args constructor
public Data() {
System.out.println("No-Args Constructor");
}
public static void main(String[] args) {
Data d = new Data();
}
}

Parameterized constructor
 A constructor which has a specific number of parameters is called parameterized
constructor.
 Parameterized constructor is used to provide different values to the distinct objects.

class A{
A(int i){
System.out.println(i);
}
public static void main(String[] args){
A ob = new A(5);
}

R.M.K. College of Engineering and Technology 67


22CS202 Java Programming

Example:
package com.journaldev.constructor;
public class Data {
private String name;
public Data(String n) {
System.out.println("Parameterized Constructor");
this.name = n;
}
public String getName() {
return name;
}
public static void main(String[] args) {
Data d = new Data("Java");
System.out.println(d.getName());
}
}

Default Constructor
 A constructor is called "Default Constructor" when it does not have any parameter.

Purpose of default constructor


 Default constructor is used to provide the default values to the object like 0, null etc.
depending on the type.

class A{
int a;
float b;
public static void main(String[] args){
A ob = new A();
System.out.println(ob.a);
System.out.println(ob.b);
}
}

Example:
package com.journaldev.constructor;
public class Data {
public static void main(String[] args) {
Data d = new Data();
}
}

1. Default constructor only role is to initialize the object and return it to the calling code.
2. Default constructor is always without argument and provided by java compiler only
when there is no existing constructor defined.
3. Most of the time we are fine with default constructor itself as other properties can be
accessed and initialized through getter setter methods.

R.M.K. College of Engineering and Technology 68


22CS202 Java Programming

1.13 Constructor Overloading


 Constructor overloading in Java is a technique of having more than one constructor
with different parameter lists.
 They are arranged in a way that each constructor performs a different task.
 They are differentiated by,
o The number of parameters in the list.
o Type of parameters.

Example
class Student
{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;
name = n;
}
Student(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}

Difference between constructor and method


Constructor Method
A constructor is used to initialize the state of A method is used to expose the behavior of
an object. an object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The java compiler provides a default The method is not provided by the compiler
constructor if you do not have any in any case.
constructor in a class.
The constructor’s name must be same as the The method name may or may not be same
class name. as class name.

R.M.K. College of Engineering and Technology 69


22CS202 Java Programming

1.14 Method Overloading in Java


 The method in Java is a collection of instructions that performs a specific task. It
provides the reusability of code.
 The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments. It has six components that are known
as method header.
 If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.
 If we must perform only one operation, having same name of the methods
increases the readability of the program.
 Suppose you must perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a (int, int) for two
parameters, and b (int, int, int) for three parameters then it may be difficult for you
as well as other programmers to understand the behavior of the method because its
name differs.

Advantage of method overloading


 Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java
 By changing the number of arguments
 By changing the data type

Method Overloading: Changing the number of arguments


In this example, we have created two methods, first, add() method performs the
addition of two numbers and second add method performs the addition of three numbers.

Example

class Adder
{
int add(int a,int b)
{
return a+b;
}
int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
Adder a=new Adder();
System.out.println(a.add(11,11));
System.out.println(a.add(11,11,11));
}

R.M.K. College of Engineering and Technology 70


22CS202 Java Programming

}
Output
22
33
Method Overloading: Changing data type of arguments
In this example, we have created two methods that differ in data type. The first add
method receives two integer arguments and the second add method receives two double
arguments.

Example
class Adder
{
int add(int a, int b)
{
return a+b;
}
double add(double a, double b)
{
return a+b;
}
}
class TestOverloading
{
public static void main(String[] args)
{
Adder a=new Adder();
System.out.println(a.add(11,11));
System.out.println(a.add(12.3,12.6));
}
}

Output
22
24.9

Can we overload java main() method?


 Yes, by method overloading.
 You can have any number of main methods in a class by method overloading. But
JVM calls main() method which receives string array as arguments only.

Example:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}

Output:
main with String[]

R.M.K. College of Engineering and Technology 71


22CS202 Java Programming

Method Overloading and Type Promotion


One type is promoted to another implicitly if no matching datatype is found. Let us
understand the concept by the figure given below:
 Byte can be promoted to short, int, long, float or double.
 The short datatype can be promoted to int, long, float or double.
 The char datatype can be promoted to int, long, float or double and so on.

Example of Method Overloading with TypePromotion


class OverloadingCalculation1{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);

}
}
Output:40
60

Example of Method Overloading with Type Promotion if matching found


 If there are matching type arguments in the method, type promotion is not performed.

class OverloadingCalculation2{
void sum(int a,int b){System.out.println("int arg method invoked");}
void sum(long a,long b){System.out.println("long arg method invoked");}

public static void main(String args[]){


OverloadingCalculation2 obj=new OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked

R.M.K. College of Engineering and Technology 72


22CS202 Java Programming

}
}
Output: int arg method invoked

Example of Method Overloading with Type Promotion in case of ambiguity


 If there are no matching type arguments in the method, and each method promotes
similar number of arguments, there will be ambiguity.

class OverloadingCalculation3{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}

public static void main(String args[]){


OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}

Output: Compile Time Error

1.15 this keyword in Java


In Java, this is a reference variable that refers to the current object.

Usage of Java this keyword


1. this can be used to refer current class instance variable.
2. this can be used to invoke the current class method (implicitly)
3. this() can be used to invoke the current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as an argument in the constructor call.
6. this can be used to return the current class instance from the method.

this: to refer current class instance variable


The “this” keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the problem
of ambiguity.

Example
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)

R.M.K. College of Engineering and Technology 73


22CS202 Java Programming

{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

Output
111 ankit 5000.0
112 sumit 6000.0

1.16 Static Keyword


The static keyword in Java is used for memory management
mainly. We can apply static keywords with variables, methods, blocks, and nested classes.
The static keyword belongs to the class than an instance of the
class.

The static can be:


1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block

Java static variable


If you declare any variable as static, it is known as a static
variable.
 The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, the
college name of students, etc.
 The static variable gets memory only once in the class area at the time of class
loading.

Advantages of static variable


 It makes your program memory efficient (i.e., it saves memory).

Program of a counter by static variable

R.M.K. College of Engineering and Technology 74


22CS202 Java Programming

The static variable will get the memory only once, if an object changes the value of
the static variable, it will retain its value.

//Java Program to illustrate the use of static variables which is shared with all objects.
class Counter2
{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;//incrementing the value of the static variable
System.out.println(count);
}
public static void main(String args[]){
//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output
1
2
3

Java static method


If you apply a static keyword with any method, it is known as a static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data members and can change their value of it.

Example of static method


//Java Program to get the cube of a given number using the static method

class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output
125

Java static block


 In Java, static blocks are used to initialize the static variables. For example,
class Test {

R.M.K. College of Engineering and Technology 75


22CS202 Java Programming

// static variable
static int age;
// static block
static {
age = 23;
}
}
 Here we can see that we have used a static block with the syntax
static {
// variable initialization
}
 The static block is executed only once when the class is loaded in memory.
 The class is loaded if either the object of the class is requested in code or the static
members are requested in code.

1.17 Final Keyword


 The final keyword is a non-access modifier used for classes, attributes, and methods,
which makes them non-changeable (impossible to inherit or override).
 The final keyword is useful when you want a variable to always store the same value,
like PI (3.14159...).
 The final keyword is called a "modifier".
 the final is a keyword and it is used with the following things.
o With variable (to create constant)
o With method (to avoid method overriding)
o With class (to avoid inheritance).
 The final keyword can be applied to the variables, a final variable that have no value
is called a blank final variable or uninitialized final variable.
 It can be initialized in the constructor only. The blank final variable can be static also
which will be initialized in the static block only.

Advantages:
 Stop value change
 Stop method overriding
 Stop inheritance

final with variables


When a variable defined with the final keyword, it becomes a constant, and it does not allow
us to modify the value. The variable defined with the final keyword allows only a one-time
assignment, once a value assigned to it, never allows us to change it again.

public class FinalVariableExample {


public static void main(String[] args) {
final int a = 10;
System.out.println("a = " + a);
a = 100; // Can't be modified
}
}

R.M.K. College of Engineering and Technology 76


22CS202 Java Programming

final with methods


When a method defined with the final keyword, it does not allow it to override. The final
method extends to the child class, but the child class cannot override or re-define it. It must
be used as it has implemented in the parent class.

class ParentClass{
int num = 10;
final void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
public class FinalKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.showData();
}
}

final with class


When a class defined with final keyword, it cannot be extended by any other class.

final class ParentClass{


int num = 10;
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass{
}
public class FinalKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
}
}

Java Reserved Keywords


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

R.M.K. College of Engineering and Technology 77


22CS202 Java Programming

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 and 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
A data type that can store whole numbers from 1.7e−308 to
double
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 a class (indicates that a class is inherited from another
extends
class)
A non-access modifier used for classes, attributes, and methods,
final
which makes them non-changeable (impossible to inherit or override)
Used with exceptions, a block of code that will be executed no
finally
matter if there is an exception or not
A data type that can store whole numbers from 3.4e−038 to
float
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
Checks whether an object is an instance of a specific class or an
instanceof
interface
A data type that can store whole numbers from -2147483648 to
int
2147483647
Used to declare a special type of class that only contains abstract
interface
methods
A data type that can store whole numbers from -
long
9223372036854775808 to 9223372036854775808
module Declares a module. New in Java 9
Specifies that a method is not implemented in the same Java source
native
file (but in another language)
new Creates new objects
package Declares a package
private An access modifier used for attributes, methods, and constructors,

R.M.K. College of Engineering and Technology 78


22CS202 Java Programming

making them only accessible within the declared class


An access modifier used for attributes, methods, and constructors,
protected
making them accessible in the same package and subclasses
An access modifier used for classes, attributes, methods, and
public
constructors, making them accessible by any other class
requires Specifies required libraries inside a module. New in Java 9
Finished the execution of a method, and can be used to return a
return
value from a method
short A data type that can store whole numbers from -32768 to 32767
A non-access modifier used for methods and attributes. Static
static methods/attributes can be accessed without creating an object of a
class
strictfp 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
A non-access modifier, which specifies that methods can only be
synchronized
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
A non-access modifier, which specifies that an attribute is not part of
transient
an object's persistent state
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
Indicates that an attribute is not cached thread-locally, and is always
volatile
read from the "main memory"
while Creates a while loop

Note: true, false, and null are not keywords, but they are literals and reserved words that
cannot be used as identifiers.

R.M.K. College of Engineering and Technology 79

You might also like