22CS202 Java Programming Unit 1 Digital Notes
22CS202 Java Programming Unit 1 Digital Notes
22CS202 Java Programming Unit 1 Digital Notes
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
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
11 Part B Questions 81
13 Real-Time Applications 83
15 Assessment Schedule 85
5
1. Course Objectives
L T P C
22CS202 JAVA PROGRAMMING
3 0 2 4
OBJECTIVES:
6
2. Syllabus
L T P C
22CS202 JAVA PROGRAMMING
3 0 2 4
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:
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
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
14
Take up the following Quiz
a) x || z
b) y || (y && z)
c) x || y
d) y && x
15
8. Lecture Notes
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.
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.
17
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
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
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.
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
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!
}
}
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
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.
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.
class Welcome
{
public static void main(String[] args)
{
System.out.println("Hello World! Welcome to Java Programming!");
}
}
Output
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
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;
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;
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
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.
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.
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;
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:
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.
Unary Operators
Unary operators act upon only one operand and perform operations such as
increment, decrement, negating an expression, or inverting a Boolean value.
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.
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.
Ternary Operator
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.
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
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.
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
The decimal number is equal to the sum of binary digits (dn) times their power of 2
(2n).
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.
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.
After left shifting by 1 bit, the result becomes 00000000 00000000 00000000
000010100 which is 20.
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
After right shifting by 1 bit, the result becomes 00000000 00000000 00000000
00000101 which is 5.
Example of a negative number
After right shifting by 1 bit, the result becomes 11111111 11111111 11111111
11111011 which is -5.
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
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.
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
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
}
}
}
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
}
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
41
}
else
{
// block of code to be executed if the condition1 is false and condition2 is false
}
Output
C grade
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");
}
}
}
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
➢ 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
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
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:
Example 3
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.
47
Syntax:
while (condition)
{
//code to be executed
Increment/decrement statement
}
Example 1
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
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
Output
1
2
3
4
5
6
7
8
9
10
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
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
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
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.
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
Output
53
10
20
70
40
50
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
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[][];
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
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
57
3
4
Multiplying the matrices...
The product is:
7 10
15 22
➢ Fields / Variable
➢ Methods
➢ Constructors
➢ Blocks
➢ Nested class and interface
Example
class Sample
{
int a,b; //variable declaration
public:
void get(); //method1
void display(); //method2
}
58
Syntax
return_type method_name(argument_list)
{
//statements;
}
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.
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
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”+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
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.
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
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
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
Java provides four Access Modifiers to set access levels for classes, variables, methods,
and constructors.
67
Public Yes Yes Yes Yes
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.
68
Advantages of static variable
➢ It makes your program memory efficient (i.e., it saves memory).
//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
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
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.");
}
}
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:
Input format
The input consists of the income earned.
Output format
The output displays the total tax to be paid.
Question 2:
Expected Output:
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.
74
Secure.
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.
75
double
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
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).
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;
}
}
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)
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:
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
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.
Output Format
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.
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