22CS202 Java Programming Unit 1 Digital Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 90

1

2
Please read this disclaimer before proceeding:
This document is confidential and intended solely for the educational
purpose of RMK Group of Educational Institutions. If you have received this
document through email in error, please notify the system manager. This
document contains proprietary information and is intended only for the
respective group/learning community as intended. If you are not the
addressee you should not disseminate, distribute, or copy through e-mail.
Please notify the sender immediately by e-mail if you have received this
document by mistake and delete this document from your system. If you
are not the intended recipient you are notified that disclosing, copying,
distributing, or taking any action in reliance on the contents of this
information is strictly prohibited.

3
22CS202 Java Programming

Department : All branches except CE


Batch / Year : 2023 – 2027 / I
Created by : Subject Handling Faculties
Date : 28.01.2024

4
Table of Contents
Sl.No. Topic Page No.

1 Course Objectives 6

2 Syllabus 7

3 Pre-requisites 10

4 Course outcomes 11

5 CO- PO Mapping 12

6 Lecture Plan 13

7 Activity-based learning 14

8 Lecture Notes 16

9 Assignments 72

10 Part A Questions & Answers 74

11 Part B Questions 81

12 Supportive Online Certifications 82

13 Real-Time Applications 83

14 Contents Beyond the Syllabus 84

15 Assessment Schedule 85

16 Prescribed Text Books & Reference Books 86

17 Mini Project suggestions 87

5
1. Course Objectives
L T P C
22CS202 JAVA PROGRAMMING
3 0 2 4

OBJECTIVES:

To explain object-oriented programming concepts and fundamentals of Java.


To apply the principles of packages, interfaces, and exceptions.
To develop a Java application with I/O streams, threads, and generic
programming.
To build applications using strings and collections.
To apply the JDBC concepts.

6
2. Syllabus
L T P C
22CS202 JAVA PROGRAMMING
3 0 2 4

UNIT I JAVA FUNDAMENTALS 15


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.

List of Exercise/Experiments:
1. Develop a Java application to generate Electricity bill. You must use one super
class called EB Bill and must have two sub classes namely Domestic Bill and
Commercial Bill. Create a class with the following members: Consumer no.,
consumer name, previous month reading, current month reading, type of EB
connection (i.e domestic or commercial). Compute the bill amount using the
following tariff
If the type of the EB connection is domestic, calculate the amount to be paid as
follows:
First 100 units - Rs. 1 per unit
101-200 units - Rs. 2.50 per unit
201 -500 units - Rs. 4 per unit
> 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid
as follows:
First 100 units - Rs. 2 per unit
101-200 units - Rs. 4.50 per unit
201 -500 units - Rs. 6 per unit
> 501 units - Rs. 7 per unit
2. Arrays Manipulations: (Use Methods for implementing these in a Class)
a. Find kth smallest element in an unsorted array
b. Find the sub array with given sum
c. Matrix manipulations – Addition, Subtraction, Multiplication
d. Remove duplicate elements in an Array
e. Accept an integer value N and print the Nth digit in the integer sequence 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 and so on till infinity.
Example: The 11th digit in the sequence 12345678910111213…. is 0.
UNIT II INHERITANCE, INTERFACES AND EXCEPTION HANDLING 15
Inheritance: Inheritance basics, Using super, Method Overriding, Using Abstract
Classes, Using final with Inheritance - Package and Interfaces: Packages, Packages and
member access, Importing Packages, Interfaces, Static Methods in an Interface –
Exception Handling: Exception-Handling Fundamentals, Exception Types, Uncaught
Exceptions, Using try and catch, Multiple catch Clauses, Nested try Statements, throw,

7
throws, finally, Java’s Built-in Exceptions.
List of Exercise/Experiments:
1. Develop a Java application with Employee class with Emp_name, Emp_id, Address,
Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant
Professor, Associate Professor and Professor from employee class. Add Basic Pay
(BP) as the member of all the inherited classes with 97% of BP as DA, 10 % of BP
as HRA, 12% of BP as PF, 0.1% of BP for staff club fund. Generate pay slips for the
employees with their gross and net salary.
2. Design a Java interface for ADT Stack. Implement this interface using array and
built-in classes. Provide necessary exception handling in both the implementations.
3. Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class
Shape. Each one of the classes contains the methods print Area () that prints the
area of the given shape and Numberofsides() that prints the number of sides of the
given shape.
4. Write a Java program to apply built-in and user defined exceptions.
UNIT III MULTITHREADING, I/O AND GENERIC PROGRAMMING 15
Multithreaded Programming: Creating a Thread, Thread Priorities, Synchronization,
Interthread Communication – I/O: I/O Basics, Reading Console Input, Writing Console
Output, Reading and Writing Files – Generics: Introduction, Generic class, Bounded
Types, Generic Methods, Generic Interfaces, Generic Restrictions.

List of Exercise/Experiments:
1. Write a Java program that correctly implements producer consumer problem using
the concept of inters thread communication.
2. Write a Java program to read and copy the content of one file to other by
handling all file related exceptions.
UNIT IV STRING HANDLING AND COLLECTIONS 15
Lambda Expressions - String Handling – Collections: The Collection Interfaces, The
Collection Classes – Iterator – Map - Regular Expression Processing.

List of Exercise/Experiments:
1. String Manipulation:
a. Reversing a set of words and count the frequency of each letter in the string.
b. Pattern Recognition - Find the number of patterns of form 1[0]1 where [0]
represents any number of zeroes (minimum requirement is one 0) there
should not be any other character except 0 in the [0] sequence in a given
binary string.
c. Remove all the occurrences of string S2 in string S1 and print the remaining.
d. Find the longest repeating sequence in a string
e. Print the number of unique string values that can be formed by rearranging

8
the letters in the string S.
2. Collections:
a. Write a program to perform string operations using ArrayList. Write functions
for the following
i. Append - add at end
ii. Insert – add at particular index
iii. Search
iv. List all string starts with given letter
b. Find the frequency of words in a given text.
UNIT V JDBC CONNECTIVITY 15
JDBC – DataSource, Configurations, Connection, Connection Pools, Driver Types,
ResultSet, Prepared Statement, Named Parameter, Embedded SQL (Insert, Update,
Delete, Join, union etc), ResultSet Navigation, Connection Close and Clean up.

List of Exercise/Experiments:
1. Mini Project (using JDBC)
TOTAL: 45+30=75 PERIODS

TEXT BOOK:
1. Herbert Schildt, “Java: The Complete Reference”, 11th Edition, McGraw Hill
Education, 2019.

REFERENCES:
1. Cay S. Horstmann, Gary Cornell, “Core Java Volume – I Fundamentals”, 11th
Edition, Prentice Hall, 2019.
2. Paul Deitel, Harvey Deitel, Java SE 8 for programmers, 3rd Edition, Pearson,
2015.
3. Steven Holzner, Java 2 Black book, Dream tech press, 2011.
4. Timothy Budd, Understanding Object-oriented programming with Java, Third
Edition, Pearson Education, 2008.
5. https://infyspringboard.onwingspan.com/web/en/app/toc/lex_2995947394736727
0000_shared/overview

9
3. Pre-requisites

10
4. Course Outcomes
At the end of this course, the students will be able to:

Course Outcomes HKL


Understand the object-oriented programming concepts and fundamentals
CO1 K2
of Java.
CO2 Develop Java programs with the packages, interfaces, and exceptions. K3
Build Java applications with I/O streams, threads, and generics
CO3 K3
programming.
CO4 Apply strings and collections in developing applications. K3

CO5 Implement the concepts of JDBC. K3

11
5. CO-PO Mapping
Course Program Outcomes
Outcomes PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

CO1 3 3 3 - - - - - - - - -

CO2 3 2 2 - - - - - - - - -

CO3 3 2 2 - - - - - - - - -

CO4 3 2 2 - - - - - - - - -

CO5 3 2 2 - - - - - - - - -

12
6. Lecture Plan: Unit 1
Sl. No. of. Proposed Actual Pertaining Taxonomy Mode of
Topic
No. Periods Date Date CO Level Delivery
An Overview of
MD 1,
1 Java, Data 1 CO1 K1
MD 4
Types
Variables and MD 1,
2 1 CO1 K1
Arrays MD 4
MD 1,
3 Operators 1 CO1 K1
MD 4
Control MD 1,
4 1 CO1 K1
Statements MD 4
Class
Fundamentals,
MD 1,
5 Declaring 1 CO1 K2
MD 4
objects,
Methods
Constructors, MD 1,
6 1 CO1 K2
this keyword MD 4
Overloading
methods, MD 1,
7 1 CO1 K3
Overloading MD 4
constructors
MD 1,
8 Access Control 1 CO1 K2
MD 4
MD 1,
9 Static, Final 1 CO1 K3
MD 4

ASSESSMENT COMPONENTS MODE OF DELEIVERY


AC 1. Unit Test MD 1. Oral presentation
AC 2. Assignment MD 2. Tutorial
AC 3. Course Seminar MD 3. Seminar
AC 4. Course Quiz MD 4. Hands On
AC 5. Case Study MD 5. Videos
AC 6. Record Work MD 6. Field Visit
AC 7. Lab / Mini Project
AC 8. Lab Model Exam
AC 9. Project Review

13
7. Activity Based Learning
Solve the puzzle to find all the keywords in java

E E D A S N U K X N A Q V F S T Y U M E
V N I B P T A N F S H Z U O S O Q Q C T
I U O S U A N E S L X Z S E A U Z A S L
T M V T E F C E L J O D A C L L F U H U
A W Q R P L R K M O N A R N C R P T O A
N M F A E T I G A E O E T A E E J R R F
I T C C M Y O H T G L B L T R W L Y T E
H H R T P T S X W J E P N S E L B U O D
T I D A O R E T U R N I M N E H C F E S
D E Z I N O R C N Y S Y S I Q O C S H W
S C H A T S E L I T A L O V N M A T C I
F T V R S E I N S T F Y W T L C P I A T
U Q A M Q T E E S I W F I N A L L Y H C
T Q X T S Y R N N D H N P T D B Q R W H
A R F R I B O H S T U T R K U W O R H T
P R O T E C T E D E S Z I P E W G N O L
N F X P I N T V N A A Z V W S W C E P E
A J F V M Y B B X V D V A Y G T R M L W
G D T L J I P B M K D T T U R D R N C A
K A E R B O K H M N U O E S Z I N E Q R

Solve the Puzzle to discover the given word

Match the following


Datatypes Size (in bytes)
char 4
byte 2
int 1
double 8

14
Take up the following Quiz

1. Write the correct order of the Java program execution


A. Class Loader
B. Interpretation
C. Compilation
D. Byte Code Verification
E. Java Source Code
F. Execution
2. Which of the following is used to load a .class file?
A. Class Loader
B. Byte Code Verifier
C. JIT Compiler
D. Interpreter
3. When a java program is compiled, it creates a
A. an obj file
B. an exe file
C. a .class file
D. a .sh file
4. The JDK is a superset of the JRE, and contains everything that is in the JRE, plus
tools such as the compilers and debuggers necessary for developing applets and
applications.
A. TRUE
B. FALSE
5. …………………….. statement provides an easy way to dispatch execution to
different parts of your code based on the value of an expression.
a) if-else
b) switch
c) if
d) while
6. Given the following Venn diagram and the variables, x, y, and z, which Java
expression most closely represents the filled-in region of the diagram?

a) x || z
b) y || (y && z)
c) x || y
d) y && x

15
8. Lecture Notes

UNIT I JAVA FUNDAMENTALS 15


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

16
1.1 An Overview of Java

What is Java?
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.

Java is one of the most popular programming languages. Some statistics about Java are
given below:
➢ Java has been evolving since 1991 with different editions
➢ According to the TIOBE Programming Community Index, it has been one of the
top 5 programming languages for the past several years
➢ It is being used by more than 10 million developers worldwide
➢ More than 15 billion devices are powered by Java technology
➢ More than 125 million Java-based TV devices have been deployed
➢ 97% of enterprise desktops run Java

The features and strengths of Java have made it suitable for applications throughout the
history of the Internet, and it continues to do so even for modern applications.

History of Java

Java was originally designed for interactive television, but it was too advanced
technology for the digital cable television industry at the time. The history of Java starts
with the Green Team. Java team members (also known as Green Team), initiated this
project to develop a language for digital devices such as set-top boxes, televisions, etc.
However, it was best suited for internet programming. Later, Java technology was
incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is
known as the father of Java, in 1995. James Gosling and his team members started the
project in the early '90s.

Currently, Java is used in internet programming, mobile devices, games, e-business


solutions, etc. Following are given significant points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like
set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the green project.

Why Java was named as "Oak"?


5) Oak is a symbol of strength and chosen as a national tree of many countries like
the U.S.A., France, Germany, Romania, etc.

17
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

Why Java Programming named "Java"?


7) The team gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that
reflected the essence of the technology: revolutionary, dynamic, lively, cool,
unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk".
Since Java was so unique, most of the team members preferred Java than other
names.
8) Java is an island in Indonesia where the first coffee was produced (called Java
coffee). It is a kind of espresso bean. Java name was chosen by James Gosling
while having a cup of coffee nearby his office.
9) Notice that Java is just a name, not an acronym.
10)Initially developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
11)In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12)JDK 1.0 was released on January 23, 1996. After the first release of Java, there
have been many additional features added to the language. Now Java is being
used in Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.

Introduction to Java

Java was the brainchild of James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Frank Sheridan. The origin of Java can be traced back to the fall of 1992 and was
initially called Oak. Oak was renamed as Java in 1995. Java was originally meant to be a
platform neutral language for embedded software in devices. The goal was to move
away from platform and OS specific compilers that would compile source for a particular
target platform to a language that would be portable, and platform independent. The
language could be used to produce platform neutral code

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
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)

18
Structure of Java Program

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

19
/*
Here is a block comment
*/

Documentation Comment:
The JDK javadoc tool uses doc comments when preparing automatically generated
documentation.
/**
documentation comments
*/

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;

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 has to 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

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

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.

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”);
}
}

20
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!
}
}

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


(Refer:https://www.youtube.com/watch?v=zBF1M8dTftk)

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

21
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=4WwBvnH9KCA
1. Download and Install IDE(Eclipse) 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

Java Language Fundamentals


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

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;
} //end of block

22
Object Oriented Programming
Object Oriented Programming is a paradigm (pattern) that provides many
concepts such as class, object, data abstraction, encapsulation,
inheritance, polymorphism, etc.

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
Object a 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
Abstraction the essential features of the object. In other words, it deals with the
outside view of an object (interface).
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
Encapsulation
manipulates. Encapsulation is a protective shield that prevents the
data from being 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 object.
Polymorphism
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.

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
Simple easy to learn and use.
• Most of the concepts are drawn from C++ thus making Java
learning simpler.
• Java programs cannot harm another system thus making it
Secure
secure.

23
• Java provides a secure means of creating Internet
applications.
• 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
Robust
typed 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-
Dynamic time type information that is used to verify and resolve
accesses to objects at run time.

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!

Keywords

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

You cannot use any of the following as identifiers in your programs. The
keywords const and goto are reserved, even though they are not currently
used. true, false, and null might seem like keywords, but they are literal; you cannot use
them as identifiers in your programs.
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

1.2 Data Types, Variables, and Arrays


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.

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


Boolean false 1 bit
char '\u0000' 2 bytes
byte 0 1 byte
short 0 2 bytes
int 0 4 bytes
long 0L 8 bytes
float 0.0f 4 bytes
double 0.0d 8 bytes

25
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 literals true, false
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
minimum value is -128 and the maximum value is 127. 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 minimum value is -32,768 and its
maximum value is 32,767. 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;

26
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. 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(-2^63) to 9,223,372,036,854,775,807(2^63 -1)
(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807.
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';

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

27
• Variable is a name of a memory location.
• There are three types of variables in java: local, instance, and static.
Variable declaration

In Java we can have three different scopes of variables:

1) Local Variable: Variables are declared and used inside the same method only.

2) Static Variable: Static variables are declared inside a class and can be used
outside the class with the class name and the class object. But the class name is
preferred.

3) Instance Variable: Instance variables are declared inside the class and can be
used outside class with the class object only.

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


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.

Variable Names:
• Variable names are case sensitive
• A variable's name can be any legal identifier an unlimited length sequence of
Unicode letters and digits, beginning with a letter, the dollar sign or the
underscore character
• 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

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

The Scope and Lifetime of Variables

Java allows variables to be declared within any block a block is begun with an opening
curly brace and ended by a closing curly brace. A block defines a scope A scope
determines what objects are visible to other parts of your program. It also determines
the lifetime of those objects. In Java, the two major scopes are those defined by a class
and those defined by a method.

The scope defined by a method begins with its opening curly brace. However, if that
method has parameters, they too are included within the method’s scope. A method’s
scope ends with its closing curly brace. This block of code is called the method body.

Variables declared inside a scope are not visible to code that is defined outside that
scope. Thus, when you declare a variable within a scope, you are localizing that variable
and protecting it from unauthorized access and/or modification.

29
//Demonstrate block scope
class Scope{
public static void main(String[] args){
int x; //known to all code witin main
x=10;
if(x==10){ //start new scope
int y=20; //known only to this block
//x and y both known here
System.out.println("x and y:" +x+" " +y);
x=y*2;
}
y=100; //Error y not known here
//x is still known here
System.out.println("x is"+x);
}
}

A variable will not hold its value once it has gone out of scope. Variables declared within
a method will not hold their values between calls to that method. A variable declared
within a block will lose its value when the block is left. The lifetime of a variable is
confined to its scope. If a variable declaration includes an initializer, then that variable
will be reinitialized each time the block in which it is declared is entered.

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 in order 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.

Type Conversion and Casting

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

Comments
Comments are those statements that are not executed by the compiler.
Comments can be used to provide information about variables or statements.
There are two types of comments in Java:

Single line comment


It is used to comment on only one line.
//This is a single-line comment
Example
class Welcome
{
public static void main(String args[])
{
int age = 25; // Here age is a variable
System.out.println(age);
}
}

Multi-line comment
It is used to comment on multiple lines of code.
/*This is a
multi-line comment*/
Example
class Welcome
{
public static void main(String args[])
{
/*
Given below is a variable age
and a print statement to print age
*/

31
int age = 25;
System.out.println(age);
}
}

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:


➢ Unary
➢ Arithmetic
➢ Relational
➢ Logical
➢ Ternary
➢ Assignment
➢ Bitwise

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

Arithmetic Operators

32
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
}
}

Relational operators

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

Operator Description
== 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;

33
int numTwo = 5;
System.out.println(numOne > numTwo); //Output will be true
}
}

Logical Operators
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 False False True False True
False True False True
False False False False

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.

Assignment Operator

34
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:


Operator Description
= 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
}
}

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.

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.

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

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

25 decimal = 11001 binary

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

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.

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

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 as a result 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

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

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
15 [] Array subscript
· Member selection
++ Unary post-increment Right to left
14
-- Unary post-decrement
++ Unary pre-increment Right to left
-- Unary pre-decrement
+ Unary plus
13 - Unary minus
! Unary logical negation
~ Unary bitwise complement
(type) Unary type cast
* Multiplication Left to right
12 / Division
% Modulus

38
+ Addition Left to right
11
- Subtraction
<< Bitwise left shift Left to right
10 >> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension
< Relational less than Left to right
<= Relational less than or equal
9 > 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 to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
= Assignment Right to left
+= Addition assignment
-= Subtraction assignment
1
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

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.

Selection Statements

39
The if Statement
Use the if statement to specify a block of Java code to be executed if a condition
is true.

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

The else Statement

Use the else statement to specify a block of code to be executed if the condition
is false.
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);

40
System.out.println("Enter the Two Numbers:");
num1=sc.nextInt();
num2=sc.nextInt();
if(num1>num2)
{
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.

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");
}
}
}

The else-if Statement


Use the else if statement to specify a new condition if the first condition is false.
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

41
}
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)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}

Output

C grade

Example 2 – positive, negative, or zero

42
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");
}
}
}

Java 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

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 )
{

43
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

The Java switch statement executes one statement from multiple conditions. It is
like an if-else-if ladder statement. The switch statement works with a byte, short, int,
long, enum types, String, and some wrapper types like Byte, Short, Int, and Long. Since
Java 7, you can use strings in the switch statement.

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;
}

Example
public class Main
{
public static void main(String[] args)
{
int day = 4;
switch (day)

44
{
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:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}

Output: Thursday

Iteration / Looping Statements


The Java for loop is used to iterate a part of the program several times. If the
number of iterations is fixed, it is recommended to use for loop.

There are three types of loops in Java.

➢ for loop
➢ while loop
➢ do...while loop
Loop When to use
while When the number of iterations is not known
do-while When we want the loop to execute at least once and the number of
iterations is not known
for When the number of iterations is known

for loop

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:

45
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.
Syntax
for(initialization; condition; increment/decrement)
{
//statement or code to be executed
}

Example 1

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

class Main
{
public static void main(String[] args)
{
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;

46
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
}
}

Output

Enter a number: 23
5

while loop

The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. As soon as the Boolean condition becomes false, the
loop automatically stops.

The while loop is considered a repeating if statement. If the number of iterations


is not fixed, it is recommended to use the while loop.

47
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
{
System.out.println(number + " is not an Armstrong number.");
}
}
}

Output

371 is an Armstrong number.

Example 2 //program to print table

import java.util.*;
public class Main
{

48
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

do_while loop

The Java do-while loop is used to iterate a part of the program repeatedly until
the specified condition is true. If the number of iterations is not fixed and you must
have to execute the loop at least once, it is recommended to use a do-while loop.

Java do-while loop is called an exit control loop. Therefore, unlike the while loop
and for loop, the do-while checks the condition at the end of the loop body. The Java
do-while loop is executed at least once because the condition is checked after the loop
body.

Syntax

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

49
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
10

Java Break Statement


When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.

The Java break statement is used to break the loop or switch statements. It
breaks the current flow of the program at specified conditions. In the case of the inner
loop, it breaks only the inner loop.

We can use Java break statements in all types of loops such as for loop, while
loop, and do-while loop.

Syntax
jump-statement;
break;

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

50
{
//using for loop
for(int i=1;i<=10;i++)
{
if(i==5)
{
//breaking the loop
break;
}
System.out.println(i);
}
}
}

Output

1
2
3
4

Java Continue Statement


The continue statement is used in the loop control structure when you need to
jump to the next iteration of the loop immediately. It can be used with for loop or a
while loop.

The Java continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified condition. In
the case of an inner loop, it continues the inner loop only.

We can use Java continue statements in all types of loops such as for loop, while
loop, and do-while loop.

Syntax
jump-statement;
continue;

Example

public class ContinueExample


{
public static void main(String[] args)
{
//for loop
for(int i=1;i<=10;i++)
{
if(i==5)
{

51
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}

Output

1
2
3
4
6
7
8
9
10

1.5 Arrays

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


Additionally, the elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed
set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 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

52
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


There are two types of arrays.

➢ 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 Java array.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Output

53
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
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

54
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++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("\n----Addition Result----");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{

55
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];
System.out.println("Enter the elements of 1st martix row wise \n");

56
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 martix 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 martix row wise
1
2
3
4
Enter the elements of 2nd martix row wise
1
2

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

1.6 Class in Java

A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created. It is a logical entity. It cannot be physical.

A class in Java can contain:

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

Syntax to declare a class:


class <class_name>
{
field / variable;
method;
}

Example

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

1.7 Declaring Objects


Syntax

classname objectname=new classname();

Example for declaring object

Sample s=new Sample();

1.8 Declaring Methods

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

Example for declaring method

void add(int a,int b)


{
int c=a+b;
cout<<c;
}

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

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


Method Description
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 It is used to scan the next token of the input as a double.
nextDouble()
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);
}
}

60
Output
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
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

61
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0

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.9 Constructors
Java supports a special kind of function, called “constructor,” which enables an
object to initialize itself when the object is created. Constructors have a similar name
as the class itself. They do not have a return type; the void is also not used as a return
type.

Example1: Constructor
class Rectangle
{
int length; int width;
Rectangle(int x,int y)//constructor method
{
length=x;
width=y;
}
int rectArea()
{
return(length*width);
}
}

class RectangleArea
{
public static void main (String args[])
{
Rectangle rect1=new Rectangle(15,10);//calling constructorconstructor
int area1=rect1.rectArea();
System.out.println(“Area =” +area1);
}
}
Example 2: (default Constructor and Parameterized Constructor)
The default constructor will not have any parameters whereas parameterized

62
constructor can have one or more parameters. A copy constructor is a special kind of
constructor where the old object is passed as an argument for the new object.

Example

class complex
{
double real,imag;
complex() //simple or default constructor
{
real=0.0;
imag=0.0;
}
complex(double x,double y) //parameterized constructor
{
real=x;
imag=y;
}
complex add(complex a) //copy constructor
{
complex n=new complex();

n.real=this.real+a.real;
n.imag=this.imag+a.imag;
return n;
}
void display()
{
System.out.println(“The result is”+real+”+i”+imag);
}
}
class comclass
{
public static void main(String args[])
{
complex c1=new complex(10,20);
complex c2=new complex(10,20);
complex c1=new complex();
c3=c1.add(c2);
c3.display();
}
}

Output
The result is 20.0+i40.0

1.10 this keyword in Java


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

63
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)
{
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();
}
}

64
Output
111 ankit 5000.0
112 sumit 6000.0

1.11 Method Overloading in Java


If a class has multiple methods having the same name but different parameters,
it is known as Method Overloading.

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 no. 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));
}
}
Output
22
33

65
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

1.12 Constructor Overloading


Creating two or more constructors with different parameters is called constructor
overloading.
Example
class Main
{
String language;
// constructor with no parameter
Main()
{
language = "Java";
}
// constructor with a single parameter
Main(String lang)
{

66
language = lang;
}
public void getName()
{
System.out.println("Programming Langauage: " + language);
}
public static void main(String[] args)
{
// call constructor with no parameter
Main obj1 = new Main();
// call constructor with a single parameter
Main obj2 = new Main("Python");
obj1.getName();
obj2.getName();
}
}

Output

Programming Language: Java


Programming Language: Python

1.13 Access Controls / Access Specifier / Access Modifier

Java provides four Access Modifiers to set access levels for classes, variables, methods,
and constructors.

The four access levels are


1. default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package No modifiers are needed.
2. private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
3. public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
4. protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
Within
Package Outside Outside
Access (Both sub Package Package
Within Class
Modifier class and (Sub class (Non-sub
non-sub Only) class Only)
class)
Private Yes No No No
Default Yes Yes No No
Protected Yes Yes Yes No

67
Public Yes Yes Yes Yes

Non access modifiers

Java has seven Non-Access Modifiers. Non-Access Modifiers are used with classes,
methods, variables, constructors. Non-Access Modifiers are used to provide information
to JVM.

Seven Non-Access Modifiers are:


1. Static: The static keyword in Java is used for memory management mainly. We
can apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class
2. Final: The final keyword in java is used to restrict the user. The java final
keyword can be used in many contexts. Final can be variable, method and class.
3. Abstract: The abstract keyword is used to achieve abstraction in Java. It is a
non-access modifier which is used to create abstract class and method. The role
of an abstract class is to contain abstract methods
4. Synchronized: Java programming language provides a very handy way of
creating threads and synchronizing their task by using synchronized blocks to
keep shared resources.
5. Transient: Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.
6. Volatile: Volatile keyword is used to modify the value of a variable (either
primitive type or objects) by different threads. It is also used to make classes
thread safe.
7. Native: The native keyword is applied to a method to indicate that the method is
implemented in native code using JNI (Java Native Interface). Native is a modifier
applicable only for methods and cannot apply it anywhere else. The methods
which are implemented in C, C++ are called as native methods or foreign
methods.

1.14 Java 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)

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.

68
Advantages of static variable
➢ It makes your program memory efficient (i.e., it saves memory).

Program of a counter by static variable


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

69
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output
125

1.15 Final Keyword in Java


The final keyword in java is used to restrict the user. The java final keyword can be
used in many contexts. The Final can be:
1. variable
2. method
3. class
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.

Java final variable


If you make any variable final, you cannot change the value of a final variable (It will be
constant).
Example of final variable
There is a final variable AGE, we are going to change the value of this variable, but it
cannot be changed because the final variable once assigned a value can never be
changed.
Example
class Main
{
public static void main(String[] args)
{
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
}
}

Output

70
cannot assign a value to final variable AGE
AGE = 45;
^
Java final method
If you make any method final, you cannot override it.
Example
class FinalDemo
{
// create a final method
public final void display()
{
System.out.println("This is a final method.");
}
}

class Main extends FinalDemo


{
// try to override final method
public final void display()
{
System.out.println("The final method is overridden.");
}
public static void main(String[] args)
{
Main obj = new Main();
obj.display();
}
}

In the above example, we have created a final method named display() inside the
FinalDemo class. Here, the Main class inherits the FinalDemo class.
We have tried to override the final method in the Main class. When we run the
program, we will get a compilation error with the following message.
Output
display() in Main cannot override display() in FinalDemo
public final void display() {
^
overridden method is final

71
9. Assignments
Question 1:
Write a java program to calculate the income tax to be paid by the employee as per the
criteria given below:

Slab rate IT rate


Upto Rs. 50,000 Nil
Upto Rs. 60,000 10% on additional amount
Upto Rs. 1,50,000 20% on additional amount
Above Rs. 1,50,000 30% on additional amount

Input format
The input consists of the income earned.

Output format
The output displays the total tax to be paid.

Question 2:

Write a Java method to check whether a string is a valid password.


Password rules:
A password must have at least ten characters.
A password consists of only letters and digits.
A password must contain at least two digits.

Expected Output:

1. A password must have at least eight characters.


2. A password consists of only letters and digits.
3. A password must contain at least two digits
Input a password (You are agreeing to the above Terms and Conditions.): abcd1234
Password is valid: abcd1234

Question 3:

Design a class for a bank database the database should support the following operations.
1. Deposit a certain amount into an account,
2. Withdrawing a certain amount from an account,
3. Return a value specifying the amount (i.e. balance) in an amount.

72
Question 4:

Create a class employee with data members employee ID, employee name, designation
and salary. Write methods get employee ()- To take user input, show Grade ()- to display
grade of employee based on salary, show_employee () to display employee details.

Question 5:
Write a Java program that reads a floating-point number. If the number is zero it prints
"zero", otherwise, print "positive" or "negative". Add "small" if the absolute value of the
number is less than 1, or "large" if it exceeds 1,000,000.

Test Data
Input a number: -2534
Expected Output:

Negative

73
10. Part A Questions & Answers
1. What are the basic concepts of OOPS? (K1, CO1)
The basic concepts of OOPS are,
Objects.
Classes.
Data abstraction and Encapsulation.
Inheritance.
Polymorphism.
Dynamic binding.
Message passing.

2. What is an object? (K2, CO1)


An object is basic run-time entity in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the
program has to handle. Each object has the data and code to manipulate the
data and theses objects interact with each other.

3. What is a class? (K2, CO1)


A class is a collection of objects of similar type. Once a class has been defined,
we can create any number of objects belonging to the class. Class is a user-
defined data type and behaves like built-in types of the programming language.

4. What is an encapsulation? (K2, CO1)


Wrapping up of data and function within the structure is called as encapsulation.
The insulation of data from direct access by the program is called as data hiding
or information binding. The data is not accessible to the outside world and only
those functions, which are wrapped in the class, can access it.

5. What is meant by dynamic binding or late binding? (K3, CO1)


Dynamic binding means that the code associated with a given procedure call is
not known until the time of the call at the run-time.

6. Write the process of programming in an object-oriented language? (K4, CO1)


The process of programming in an object-oriented language are,
Create classes that define objects and their behaviour.
Creating objects from class definition.
Establishing communication among objects.

7. What are the features of Java? (K2, CO1)


The features of Java are,
Simple.
Object Oriented.
Platform Independent.
Robust.
Multithreaded.

74
Secure.

8. What is meant by virtual machine? (K2, CO1)


A Java virtual machine (JVM), an implementation of the Java Virtual Machine
Specification, interprets compiled Java binary code (called bytecode) for a
computer's processor (or "hardware platform") so that it can perform a Java
program's instructions.

9. What are the two components of Java platform? (K1, CO1)


The two components of Java platform are,
The Java Virtual Machine
The Java Application Programming Interface (API)

10. What is bytecode in Java? (K2, CO1)


Java bytecode is the form of instructions that the Java virtual machine executes.
Each bytecode opcode is one byte in length, although some require parameters,
resulting in some multi-byte instructions. Not all the possible 256 opcodes are
used.

11. What is an Object and how do you allocate memory to it? (K3, CO1)
Object is an instance of a class and it is a software unit that combines a
structured set of data with a set of operations for inspecting and manipulating
that data. When an object is created using new operator, memory is allocated to
it.

12. What are different types of access modifiers? (K1, CO1)


The different types of access modifiers are,
public: Anything declared as public can be accessed from anywhere.
private: Anything declared as private cannot be seen outside of its class.
protected: Anything declared as protected can be accessed by classes in
the same package and subclasses in the other packages.
default modifier: Can be accessed only to classes in the same package.

13. What is method overloading and method overriding? (K2, CO1)


Method overloading: When a method in a class having the same method name
with different arguments is said to be method overloading. Method overriding:
When a method in a class having the same method name with same arguments
is said to be method overriding.

14. List out the primitive types in Java. (K1, CO1)


The eight primitive types are listed:
boolean
char
byte
short
int
long
float

75
double

15. What is an array? (K2, CO1)


An array is a special object containing a group of contiguous memory locations
that have the same name and the same type and a separate variable containing
an integer constant equal to the number of array elements. The elements of Java
arrays are numbered starting from 0.
Example: double x [];
x = new double [5];
// create an array reference
// create array object

16. Why Java use Unicode? (K2, CO1)


Java use Unicode to represent a character. Unicode defines a fully international
character set that can represent all the characters found in all human languages.

17. What is Classpath? (K2, CO1)


The Classpath is an argument we can set either on the command-line, or through
an environment variable that tells the Java Virtual Machine where to look for user
defined classes and packages when running Java programs.

18. What is Garbage collection? (K2, CO1)


The Garbage collection is the process that is used to free the memory of the
objects that are no longer in use. When a program stops referencing an object, it
is not required anymore and can be deleted. The space that is used by the object
is released for use by another object.

19. Define Class. (K1, CO1)


Classes are basic concepts of Object-Oriented Programming which revolve around
the real life entities.
A class is a blueprint / template / prototype for creating objects.
A class used to define user defined data-type.
A class is a collection of data members (Fields) and member functions
(Methods).

20. What is an Object and how does memory allocation is done? (K1, CO1)
Object is an instance of a class and it is a software unit that combines a
structured set of data with a set of operations for inspecting and manipulating
that data. Memory is allocated for an object using new operator.

21. Write the syntax to define a class in Java. Give Example. (K2, CO1)
Defining a class in Java is done using the syntax
[Access Modifier] class <ClassName>
{
field; method;
}
Example:
public class Dog{

76
String breed; int age;
String color; void barking()
{}
void hungry()
{}
void sleeping()
{}
}

22. What are the different types of classes in Java? (K1, CO1)
Different types of classes supported by java are
Concrete Class
abstract Class
final Class
static Class
Inner Class

23. Define concrete class. (K1, CO1)


Any normal class which does not have any abstract method or a class that has an
implementation of all the methods of its parent class or interface and its own
methods is a concrete class.

24. Define abstract class. (K1, CO1)


A class declared with abstract keyword and have zero or more abstract methods
are known as abstract class. The abstract classes are incomplete classes.
Therefore, to use, strictly need to extend the abstract classes to a concrete class.

25. Define final class. (K1, CO1)


A class declared with the final keyword is a final class and it cannot be extended
by another class, for example java.lang.System class.

26. Define static class. (K1, CO1)


Static classes are nested classes means a class declared within another class as a
static member is called a static class.

27. Define inner Class. (K1, CO1)


Java inner class or nested class is a class which is declared inside the class or
interface. We use inner classes to logically group classes and interfaces in one
place so that it can be more readable and maintainable.

28. Write the significance of constructor in Java. List out its type. (K1, CO1)
Main purpose of a constructor is to initialize the instance variables of a class.
There are two types of constructors
Parameterized constructor - This accepts parameters. usually, using this
programmer can initialize the instance variables dynamically with the
values specified at the time of instantiation.

77
Default constructor - This is a constructor which can be called with no
arguments (either defined with an empty parameter list, or with default
arguments provided for every parameter).

29. Give brief note on Overloaded constructor. (K1, CO1)


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 the compiler by
the number of parameters in the list and their types.

30. Write a code snipped in Java to illustrate Overloaded constructor. (K2, CO1)
class Box{
double width, height, depth;
// constructor used when all dimensions specified
Box(double w, double h, double d){
width = w; height = h; depth = d;
}
// constructor used when no dimensions specified
Box(){
width = height = depth = 0;
}
// constructor used when cube is created
Box(double len){
width = height = depth = len;
}
}

31. What is method in Java? Give its Benefit. (K1, CO1)


Method is a collection of statements that perform some specific tasks and return
the result to the caller. A method can perform some specific tasks without
returning anything. Methods allow us to reuse the code without retyping the
code. In Java, every method must be part of some class.

32. How a method is declared in Java? (K2, CO1)


Method in Java is declared using the Syntax
[access-specifier] [modifier] return-type method_name ([parameter list])
{
body of the function/method;
}
method declarations have six components:
Access specifier
Modifier
Return-Type
Method_name
Parameter list
Method Body

33. Write a code snippet to illustrate method is declared in Java. (K2, CO1)

78
public static void myMethod(){
System.out.println("My Function called");
}
Access specifier - public
Modifier – static
Return-Type - void
Method_name - myMethod
Parameter list – empty
Method Body
34. Write a note on protected access modifier in Java. (K1, CO1)
The access level of a protected modifier is within the package and outside the
package through child class. Without making the child class, it cannot be
accessed from outside the package.

35. Write a simple program illustrate usage of method in Java. (K2, CO1)
public class methodDemo{
public static void myMethod(){
System.out.println("My Function called");
}
public static void main(String[] args){
System.out.println("About to encounter a method.");
myMethod(); // method call
System.out.println("Method was executed successfully!");
}
}

36. Write a note on static non access modifier in Java. (K1, CO1)
In Java, static members are those which belongs to the class and they can be
accessed without instantiating the class. The static keyword can be used with
methods, fields, classes (inner/nested) and blocks. Static Methods can be created
by using the keyword static.

37. Illustrate the usage of comment statement using a simple program. (K2, CO1)
/* This is an example of multi-line comment.
The program prints "Hello, World!" to the standard output. */
class HelloWorld{
public static void main(String[] args){
// Next statement is print – This is single line comment.
System.out.println("Hello, World!");
}
}

38. What are the data types supported in Java. (K1, CO1)
Java Data Types
Primitive data types - byte, short, int, long, float, double, boolean and
char.
Non-primitive data types - such as String, Arrays, Classes, etc.

79
39. Give brief note on variables in Java. (K1, CO1)
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type. Variable is a name of memory
location. There are three types of variables in java: local, instance and static.

80
11. Part B Questions
1. What is method? How method is defined? give example (K2, CO1)
2. What is class? How do you define a class in java (K1, CO1)
3. Explain arrays in java? (K1, CO1)
4. Explain the features of Java and list out the characteristics of JAVA (K1, CO1)
5. Explain the characteristics of OOPs (K1, CO1)
6. Summarize the types of constructors supported by JAVA with example. (K2, CO1)
7. Discuss the usage of constructor with an example using java (K1, CO1)
8. Explain the object constructors and calling other constructor with example (K2, CO1)
9. With relevant examples describe abstraction and encapsulation. Write a java
program that uses an abstraction and encapsulation. (K2, CO1)
10. Illustrate what is polymorphism? Write a java program that implements
Polymorphism. (K3, CO1)
11. Illustrate with an example the following features of constructors: (K3, CO1)
a. Default constructors
b. Parameterized constructor
c. Overloaded constructors
d. A call to another constructor with this operator
e. An object initialization block
f. A static initialization blocks
12. Illustrate OOPS and explain the features of OOPS (K1, CO1)
13. Demonstrate the static fields and methods used in java (K3, CO1)
14. Distinguish argument and parameter? Discuss with example (K1, CO1)
15. Differentiate constructor and method with example (K3, CO1)
16. Difference between OOPS and procedural programming language (K4, CO1)
17. Assess the different methods in java.Util.Arrays class with example (K5, CO1)
18. Create a Java program for push and pop operations in stack using arrays in classes
and object. (K5, CO1)
19. Make a class Student. The student class has data members such a sroll number,
name, branch. Create a class called Exam that has data members roll number and
six subject marks. Derive the result class from Student and Exam it has own data
members such a total mark, and result. Write a Java program to model the
relationships. (K5, CO1)
20. Create a java program to find a smallest number in the given array by Creating one
dimensional array and two-dimensional array using new operator. (K4, CO1)
a. Write a Java program to Evaluate the following series 1-2+3- 4+…+n.
b. Write a Java program to test the prime numbers between the given two limits.
21. Write a program to perform the following functions using classes, objects,
constructors, and destructors where essential (K4, CO1)
a. Get as input the marks of 5students in 5 subjects
b. Calculate the total and average
c. Print the formatted result on the screen

81
12. Supportive Online Certifications
1. Java Programming for Complete Beginners (OOP):
https://www.udemy.com/share/105Ats3@0ihDNwNajTREMVRUKO5OZQBFqE57C
7TcUhT9liymUjs_zni1gvevblAxFwUhVeBv/ (Paid)

2. Java for Beginners - Learn all the Basics of Java:


https://www.udemy.com/share/103YNW3@kIxBijf_pcxLMadzgPrPq_Sx8vmtTpsCZ
RME7XW-rjqRWVCgemKUG_lYI463p1M6/ (Paid)

3. The Java Course - Learn from Scratch:


https://www.udemy.com/share/102kSU3@xljp7F5-wR3b99x7yf1RU-
lkcB_OiaCAANLmOf2PL5hvlsxvkGLYSFht_6Hrq3hp/ (Paid)

4. Java Programming Fundamentals (Infosys Springboard):


https://infyspringboard.onwingspan.com/web/en/app/toc/lex_2995947394736727
0000_shared/overview

5. Java (Basic) Skills Certification Test: https://www.hackerrank.com/skills-


verification/java_basic

6. Introduction to Java: https://www.sololearn.com/Course/Java/

7. Object Oriented Programming in Java Specialization:


https://www.coursera.org/specializations/object-oriented-programming

8. Java Programming Masterclass updated to Java 17:


https://www.udemy.com/course/java-the-complete-java-developer-course/
[Paid]

9. Programming in Java: https://nptel.ac.in/courses/106/105/106105191/ [Paid]

10. Java Learning Subscription: https://education.oracle.com/java-se-8-


fundamentals/courP_3348 [Paid]

82
13. Real Time Applications
1. Desktop GUI Programs
2. Mobile Applications
3. Artificial intelligence
4. Web based Applications
5. Big data technology
6. Gaming Applications
7. Business Applications
8. Embedded Systems
9. Cloud based Applications
10. Scientific Applications
11. Distributed Applications
12. Web servers and Application servers
13. Software Tools

83
14. Contents Beyond the Syllabus
Command Line Arguments

When you execute a java program, you can pass command line arguments in the
following way:

java Simple <argument1> <argument2>….<argument-n>

You can access these arguments in your program, using the String array that you have
passed as an argument to the main method – String[] args

class Simple {
static public void main(String[] args) {
System.out.println(args[0]);
}
}

When we compile the above code successfully and execute it as Java Simple Hello, the
output will be Hello.

class Simple {
static public void main(String[] args) {
int i1 = Integer.parseInt(args[0]);
int i2 = Integer.parseInt(args[1]);
System.out.println(i1+i2);
}
}

When we compile the above code successfully and execute it as Java Simple 10 20, the
output will be 30.

class FindNumberOfArguments {
public static void main(String[ ] args) {
int len = args.length;
System.out.println(len);
}
}

If you compile the above code successfully and execute it as java FindLength A B C D E
F, the result will be 6.

84
15. Assessment Schedule
Tentative schedule for the Assessment During 2023-2024
EVEN semester

S.NO Name of the Start Date End Date Portion


Assessment

1 Unit Test 1 - - UNIT 1

2 IAT 1 26.02.2024 02.03.2024 UNIT 1 & 2

3 Unit Test 2 - - UNIT 3

4 IAT 2 11.04.2024 17.04.2024 UNIT 3 & 4

5 Revision 1 - - UNIT 5 , 1 &


2

6 Revision 2 - - UNIT 3 & 4

7 Model 02.05.2024 11.05.2024 ALL 5 UNITS

85
16. Prescribed Text Books & Reference Books
TEXT BOOK:
1. Herbert Schildt, “Java: The Complete Reference”, 11th Edition, McGraw Hill
Education, 2019.

REFERENCES:
1. Cay S. Horstmann, Gary Cornell, “Core Java Volume – I Fundamentals”, 11th
Edition, Prentice Hall, 2019.
2. Paul Deitel, Harvey Deitel, Java SE 8 for programmers, 3rd Edition, Pearson,
2015.
3. Steven Holzner, Java 2 Black book, Dream tech press, 2011.
4. Timothy Budd, Understanding Object-oriented programming with Java, Third
Edition, Pearson Education, 2008.
5. https://infyspringboard.onwingspan.com/web/en/app/toc/lex_2995947394736727
0000_shared/overview

86
17. Mini Project suggestions
1) Ajju has a Carom board and TT table (Table Tennis). Ree needs those games. She can get
it if it gives the correct answer to the Ajju’s question. He asked an area of the carom board
and TT table. Ree needs your help, Help her to get those games from Ajju.

Input Format
Input consist of 3 integers.

First input represents the side of carrom


Second input represents length of TT table
Third input represents breadth of TT table.

Output Format

Output consist of 2 integers.

First output represents the area of carrom.


Second output represents area of TT table.

2) Seetha was shocked after seeing her electricity bill for May month. She approached the
TNEB office and asked for more details. TNEB officer explained the tariff rate and asked to
calculate and check. She was not able to calculate and asked her friend to help. Her friend
said it will be calculated based on the Max.unit. Help Seetha and her friend to calculate the
amount.

Input Format
The input consists of the number of units consumed.

Output Format
The output displays the total amount.
3) The much awaited event at the entertainment industry every year is the "Screen Awards".
This year the event is going to be organized on December 25 to honour the Artists for their
professional excellence in Cinema. The Organizers has this time decided to launch an online
portal to facilitate easy booking of the Award show’s tickets.

They specifically wanted to provide an option for bulk booking in the portal, wherein there are
many discounts announced. Write a program to help the Organizers to create the portal as
per the requirement given below. 87
Given the ticket cost as 'X'.
If the number of tickets purchased is less than 50, there is no discount.
If the number of tickets purchased is between 50 and 100 (both inclusive), then 10% discount
is offered.
If the number of tickets purchased is between 101 and 200(both inclusive), 20% discount is
offered.
If the number of tickets purchased is between 201 and 400(both inclusive), 30% discount is
offered.
If the number of tickets purchased is between 401 and 500(both inclusive), 40% discount is
offered.
If the number of tickets purchased is greater than 500, then 50% discount is offered.

Input Format
First line of the input is an integer that corresponds to the cost of the ticket ‘X’.
Second line of the input is an integer that corresponds to the number of tickets purchased.

Output Format
Output should display a double value, which gives the total expenses in purchasing the tickets
after discounts. Display the output correct to 2 decimal places.
4) We are going to check duplicate user details. In our application, there can be only one user
with a specific mobile number. If two users exist with the same mobile number they are
duplicate. How to check whether two objects are equal?.Yeah, you are right the equals()
method. Go on override the equals method and check if two users are same.

Create User class with following private attributes

1. Create Default and Parameterized Constructor as User(String name, String username,


String password,String mobileNumber) for the class.
2. Override equals method that compares mobileNumber of the two objects.
3. Create a driver class named Main to test the above class.

Input Format
Input consist of two sets of user details
Output Format
Output prints whether the two users are equal or not
5) Nurikabe logical game (sometimes called Islands in the Stream) is a binary determination
puzzle. The puzzle is played on a typically rectangular grid of cells, some of which contain
numbers. You must decide for each cell if it is white or black (by clicking on them) according
to the following rules:
· All of the black cells must be connected.
· Each numbered cell must be part of a white island of connected white cells.
· Each island must have the same number of white cells as the number it contains
(including the numbered cell).
· Two islands may not be connected.
· There cannot be any 2x2 blocks of black cells.
Unnumbered cells start out grey and cycle through white and black when clicked. Initially
numbered cells are white in color.
Problem Statement:
Write a program to check whether the given board configuration is a valid initial
configuration. Below figure is the sample valid initial configuration.

Input Format First line of the input is an integer N that gives the number of rows and
columns of the grid.
Next N lines will have the board configuration with N*N cells. Assume that the maximum
number in a cell can be 10. Grey colored cells are represented by the integer 20 in the matrix
representation of the input configuration.
Output Format
Output "Yes" (without quotes) if the given configuration is a valid initial configuration. Print
"No" otherwise (without quotes).
Refer sample input and output for formatting specifications.
Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of RMK
Group of Educational Institutions. If you have received this document through email in
error, please notify the system manager. This document contains proprietary
information and is intended only to the respective group / learning community as
intended. If you are not the addressee you should not disseminate, distribute, or copy
through e-mail. Please notify the sender immediately by e-mail if you have received this
document by mistake and delete this document from your system. If you are not the
intended recipient you are notified that disclosing, copying, distributing, or taking any
action in reliance on the contents of this information is strictly prohibited.

90

You might also like