3 Mech - Java Programming Unit 1
3 Mech - Java Programming Unit 1
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 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.
JAVA PROGRAMMING
Created by :
Dr J.Sathiamoorthy Associate Professor / CSE
Date : 08.08.2022
4
1. CONTENTS
Page
S. No. Contents
No
1 Contents 5
2 Course Objectives 6
3 Pre Requisites 7
4 Syllabus 8
5 1.
Course outcomes CONTENTS 9
7 Lecture Plan 11
9 Lecture Notes 14
10 Assignments 96
5
2. COURSE OBJECTIVES
6
3. PRE REQUISITES
Pre-requisite Chart
7
4. SYLLABUS
OUTCOMES:
At the end of this course, the students will be able to:
CO1: Understand the Object Oriented Programming concepts and fundamentals of Java
CO2: Develop Java programs with the packages, inheritance and interfaces
CO3: Build applications using Exceptions and Threads.
CO4: Build Java applications with I/O streams and generics classes
CO5: Use Strings and Collections in applications
8
5. Course Outcomes
CO4 Build Java applications with I/O streams and generics classes K3
POs/PSOs
PS O
COs PO PO PO PO PO PO PO PO PO 9 PO1 PO1 PO1 PSO 1PSO 2 3
1 2 3 4 5 6 7 8 0 1 2
CO1 3 3 3 - - - - - - - - - 3 2 2
CO2 3 2 2 - - - - - - - - - 3 2 2
CO3 3 2 2 - - - - - - - - - 3 2 2
CO4 3 2 2 - - - - - - - - - 3 2 2
CO5 3 2 2 - - - - - - - - - 3 2 2
7. Lecture Plan
UNIT - I
PPT/
Constructors, this keyword 27.08.2021
6 CO1 Demo K2
PPT/
Access Control 31.08.2021
8 CO1 Demo K2
PPT/
Static, Final 01.09.2021
9 CO1 Demo K3
8. ACTIVITY BASED LEARNING – UNIT
I
https://hr.gs/oopstest1
Overview of JAVA
1. Basic building blocks are object and 1. Basic building blocks are function
its object centric and its algorithm centric
Refer:
https://drive.google.com/file/d/1RjO6Q8PHd9hTkY3Uogz4eVc35UHIO224/view?usp=
sharing
Object Oriented Programming
Refer: https://www.youtube.com/watch?v=qwS-BCOCB-A
Objects
•Objects are real-world entity such as book, cat, house, pencil, person, etc. Any
things we see, that could be differentiated from another is called object. Objects
should have a well defined boundary. An object consists of:
Examples of Object
Every object has its own set of properties, which defines the state of the object
and its own behavior. The properties (data) and the behaviors (methods or
function that operate on the data) are combined into a single unit, so that the data
can be accessed only by those functions and not by the outside world.
Object
The value assigned to the properties defines the state of an object and also
differentiate one object from the other.
Breed = Dachshund
Age = 1 Color =
Coral Size = Small
Breed = Bulldog
Age = 2
Color = Black Size = Medium
reserveticket()
Class
•Instance variables − Instance variables are variables within a class but outside
any method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
•Class variables − Class variables are variables declared within a class, outside
any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.
Abstraction
•Abstraction is the process used to hide certain details and only show the essential
features of the object. In other words, it deals with the outside view of an object.
•Ex: A car is viewed as a car rather than its individual components. Consider a real-
life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but
he does not know about how on pressing the accelerator the speed is actually
increasing, he does not know about the inner mechanism of the car or the
implementation of accelerator, brakes etc in the car. This is what abstraction is.
Encapsulation
•Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. Encapsulation is a
protective shield that prevents the data from being accessed by the code outside
this shield.
•As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.
•Encapsulation can be achieved by declaring all the variables in the class as private
Inheritance
Class A
Class B
Class B
Class C
Hierarchical Inheritance Multiple Inheritance
Polymorphism
Method overloading is defining more than one method using same name but
having different number or type of parameters. Method overriding the redefine
the base class functions in a derived class.
Solve the cross word puzzle on Object Oriented Programming
Across
1. Redefining base class function in a derived class.
2. Parent class.
6. Advantage of inheritance.
8. Multiple forms.
9. Real-time entity.
10. Process of representing the essential features without including implementation
details.
11. The process of binding data and functions into a single unit.
12. Blueprint of an object.
13. Derived class.
Down
1. More than one function with same name
3. Define object behavior.
4. Define the state of an object.
5. Object interacts via.
7. Deriving a new class from an existing class.
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.
•Simple
• Has a concise, cohesive set of features that makes it easy to learn and use.
• Most of the concepts are drew from C++ thus making Java learning simpler.
•Secure
•Portable
• Can execute in any environment for which there is a Java run-time system.
(JVM)
•Object-oriented
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
• Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time.
• Strongly Typed
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
A. Class Loader
B. Interpretation
C. Compilation
F. Execution
A. Class Loader
C. JIT Compiler
D. Interpreter
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
Structure of Java Program
Documentation Section
/*
*/
• 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 has to be at the
beginning of the code before any class or interface declaration. This statement is
optional, for example, take a look at the statement below.
package student;
Import Statement
import java.util.Date; // Imports the Date class from util package import java.sql.*;
Interface Section
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 actually starts and follows the order
specified for the following statements. Structure of main method class
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.
Refer: https://www.youtube.com/watch?v=4WwBvnH9KCA
https://www.eclipse.org/downloads/)
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
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.
Keywords
class Test
{
public static void main(String [ ] args)
{
•Java is a strongly typed language. Each variable must have a declared type.
•Data types specify the different sizes and values that can be stored in the variable.
•These are the most basic data types available in Java Language.
Default
Data Size Maximum Range Value (for
Minimum Range
Type (in bits) fields)
boolean 1 NA NA false
2. Non-Primitive data types:
• class
• interface
• String
• array
• etc.,
3 Primitive type cannot have null Non-Primitive type can have null
Variables
•Variable is a container which holds the value while the program is executed.
1. Local Variable
2. Instance Variable
•A variable declared inside the class but outside the body of the method.
•It is called instance variable because its value is instance specific and is not
shared among instances.
3. Static Variable
•Single copy of static variable is created and share among all the instances of the
class.
•Memory allocation for static variable happens only once when the class is loaded in
the memory.
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:
•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 {
Java allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared.
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.
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.
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.
Arrays
An array is an object of reference type which contains a fixed number of
components of the same type; the length of an array is immutable. Creating an
instance of an array requires knowledge of the length and component type. Each
component may be a primitive type like byte, int, or double, a reference type like
String or Object. Multi-dimensional arrays are really just arrays which contain
components of array type. Less formally, Array is a collection of similar type of
elements which has contiguous memory location.
Advantages
•Code Optimization: Can retrieve or sort the data efficiently.
•Random access: Can get any data located at an index position.
Disadvantages
•Size Limit: Array can store only the fixed size of elements. Array cannot grow its
size at runtime.
• The variables in the array are ordered and each has an index beginning from 0.
• Java array can be also be used as a static field, a local variable or a method
parameter.
• The size of an array must be specified by an int value and not long or short.
Creating an array
• One-Dimensional Arrays
The one-dimensional array declaration is done using the syntax:
type var_name[]; or
type[] var_name;
• An array declaration has two components : the type and the name
Example
int intArray[]; or
int[] intArray;
• Like array of int type, array of other primitive data types like char, float, and
double. etc or user defined data type(objects of a class) can be created.
Instantiating an Array
Example:
or
Array Literal
When the size of the array and variables of array are already known, array
literals can be used.
•The length of this array determines the length of the created array.
•There is no need to write the new int[] part in the latest versions of Java
Accessing an array
Output:
33
3
4
5
•Two Dimensional array can be represented as the collection of rows and columns.
Syntax:
• data_type: Type of data to be stored in the array. For example: int, char,
etc.
• dimension: The dimension of the array created. For example: 1D, 2D, etc.
Syntax:
Example:
Syntax:
array_name[row_index][column_index] = value;
Example:
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[0][3] = 4;
arr[1][0] = 5;
arr[1][1] = 6;
arr[1][2] = 7;
arr[1][3] = 8;
arr[2][0] = 9;
arr[2][1] = 10;
arr[2][2] = 11;
arr[2][3] = 12;
Output:
Enter Element : 2
Enter Element : 3
Enter Element : 4
Enter Element : 5
Enter Element : 8
Enter Element : 9
Enter Element : 4
Enter Element : 6
Enter Element : 1
Printing Elements...
2 3 4
5 8 9
4 6 1
Operators
Java provides a rich set of operators to manipulate data. We can divide all the Java
operators into the following groups
•Arithmetic Operators
•Unary Operator
•Relational Operators
•Logical Operators
•Assignment Operator
•Bitwise Operators
Arithmetic Operators
+ Addition A+B
- Subtraction A-B
* Multiplication A*B
/ Division A/B
% Modulus A%B
int b = 3;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}
Output:
a + b = 13 a - b = 7
a * b = 30 a / b = 3
a % b = 1
Unary Operators
Output:
++a = 11
--b = 19
-
// Example for post increment/decrement
class Sample {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a++ = " + (a++));
System.out.println("b-- = " + (b--));
}
}
Output:
a++ = 10
b-- = 20
Relational Operators
•Relational operators are used to test condition and results true or false value. The
following table lists relational operators.
> greater than the value on the right, then the condition (A > B)
becomes true.
Two values are checked and if the value on the left is less
< than the value on the right, then the condition becomes (A < B)
true
Two values are checked and if the value on the left is
>= greater than equal to the value on the right, then the (A >= B)
condition becomes true
Two values are checked and if the value on the left is less
<= than equal to the value on the right, then the condition (A <= B)
becomes true
/* Example to understand Relational operator */
Output:
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
Logical Operators
•Logical operators are used to combine more than one condition. The
following table lists logical operators.
Output:
Assignment Operator
❖Simple Assignment
=, assigns right hand side value to left hand side variable Ex: int a;
a = 10;
❖Compound Assignment
+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=, assigns right hand side value after
the computation to left hand side variable
Ex: int a;
int b;
a += 10; // means a = a + 10; a &= b; // means a = a & b;
Bitwise Operators
Bitwise operator act on integral operands and perform binary operations. The lists of
bitwise operators are
• Bitwise OR |
• Bitwise EXOR ^
• Bitwise AND
The & operator compares corresponding bits between two numbers and if both the
bits are 1, only then the resultant bit is 1. If either one of the bits is 0, then the
resultant bit is 0.
Example :
• Bitwise OR
The | operator will set the resulting bit to 1 if either one of them is 1. It will return 0
only if both the bits are 0.
Example :
int x = 5; int y = 9;
5-> 0101
x ^ y = 12 9-> 1001
1100
Example:
public class Sample {
public static void main(String[] args) {
int x = 5; int y = 9;
int a = x & y; int b = x | y; int c = x ^ y;
Output:
x & y = 1
x | y = 13
x ^ y = 12
• Bitwise NOT
The negation ~ operators complements all the bits, 1 are converted to 0 and 0s are
converted to 1s.
Example:
int a =5;
~a = -6
5 -> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
~5 - > 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0
• Shift Operators
The shift operators (<< and >>) shift the bits of a number to the left or right,
resulting in a new number. They are used only on integral numbers (and not on
floating point numbers, i.e. decimals).
▪ Shift Right
The right shift operator (>>) is used to divide a number in the multiples of 2, while
the left shift operator(<<) is used to multiply a number in the multiples of 2.
Example:
right shift operator >>, divides by 2 to the power of number specified after the
operator. In this case, we have 3 as the value after the right shift operator. So, 16
will be divided by the value 2 to the power of 3, which is 8.
The result is 2.
When we represent 16 in binary form, we will get the following binary value :
When we0apply
0 0 0>>
0 0which
0 0 0is0the
0 0right
0 0 0shift
0 0operator,
0 0 0 0 0the
0 0bit0 represented
0 0 1 0 0 0 by
0 1 moves
by 3 positions to the right (represented by the number after the right shift
operator). After shifting the binary digit 1, we will get:
00000000000000000000000000000010
x=2
▪Shift Left
Example:
int x = 8; x = x << 4;
left shift operator <<, multiplies by 2 to the power of number specified after
the operator. In this case, we have 4 as the value after the left shift operator.
So, 8 will be multiplied by the value 2 to the power of 4, which is 16.
When we represent 8 in binary form, we will get the following binary value:
When
0 0 0we
0 0apply
0 0 <<
0 0 which
0 0 0 0is 0the
0 0left
0 shift
0 0 0operator,
0 0 0 0 the
0 0 bit
0 0represented
1 0 0 0 by 1
moves by 4 positions to the left (represented by the number after the right
shift operator). After shifting the binary digit 1, we will get:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
x=128
Example:
public class Sample {
public static void main(String[] args) { int x = 8;
System.out.println("The original value of x is " + x);
System.out.println("After using << 2, the new value is
" + (x << 2));
System.out.println("After using >> 4, the new value is " +
(x >> 4));
}
}
Output:
Flow Control
Control statements are statements which alter the normal execution flow of a
program. There are three types of Control Statements in java.
Simple if
Syntax :
if(boolean expression) {
statement–block;
Next statement;
Entry
True
boolean expression ?
statement–block
False
Next Statement
Example:
public class Sample {
public static void main(String args[]) { int x =
5;
if (x < 20) {
System.out.print("This is if
statement");
}
}
}
Output:
This is if statement
if .. else statement
The if….else statement is an extension of simple if statement
Syntax:
if(boolean expression)
{
True-block statements;
}
else
{
False-block statements;
}
Next statement;
Entry
False
True Boolean expression?
True-block False-block
Next Statement
/* program to check given age input is eligible to vote or not using if-
else*/
public class Sample {
public static void main(String[] args) { int age;
age = Integer.parseInt(args[0]); if (age > 18) {
System.out.println("Eligible to vote");
} else {
System.out.println("Not eligible to
vote");
}
}
}
Output:
Syntax:
if (condition-1) {
statement-1
}
….
else if(condition-n) {
statement-n
}
else {
default statement
}
next statement
switch case
Syntax:
switch (expression) { case value-1 : case-1 block break;
break;
statement-x;
Note: expression must return an integral value Case value
must be an integral constant
Syntax:
while(condition) false
Boolean Condition
{
true
Body of the loop
i: 0
i: 1
i: 2
i: 3
i: 4
do.. while Loop
It’s a exit controlled loop, the body of the loop gets executed first followed by
checking the condition. Continues with the body if the condition is true, else loops
gets terminated.
Syntax
true
Output:
i: 5
for Loop
The for loop initialize the value before the first step. Then checking the condition
against the current value of variable and execute the loop statement and then
perform the step taken for each execution of loop body. For-loops are also typically
used when the number of iterations is known before entering the loop.
Syntax:
loop
Output:
i: 1
i: 2
i: 3
i: 4
i: 5
i: 10
i: 20
i: 30
i: 40
i: 50
break Statement
• While the execution of program, the break statement will terminate the iteration
or switch case block.
• When a break statement is encountered in a loop, the loop is exited and the
program continues with the statements immediately following the loop.
• When the loops are nested, the break will only terminate the corresponding loop
body.
Output:
i: 1
continue Statement
Output:
i: 1
i: 2
i: 4
i: 5
Introducing Classes
•Classes are basic concepts of Object Oriented Programming which revolve around
the real life entities.
• fields
• methods
• constructors
Syntax:
fields;
methods; constructors;
This is a class declaration. The class body (the area between the braces) contains all
the code that provides for the life cycle of the objects created from the class:
constructors for initializing new objects, declarations for the fields that provide the
state of the class and its objects, and methods to implement the behavior of the
class and its objects.
Objects
Objects are basic concepts of Object Oriented Programming which revolve around
the real life entities. A Java program creates many objects, interact by invoking
methods.
Through these object interactions, a program can carry out various tasks, such as
implementing a GUI, running an animation, or sending and receiving information
over a network. Once an object has completed the work for which it was created, its
resources are recycled for use by other objects.
Creating Object
•A software object maintains its state in variables and implements its behaviour with
methods.
Syntax:
2.Instantiation: The new keyword is a Java operator that creates the object.
Syntax :
[access-specifier] [modifier] return-type function-name
([parameter list])
{
body of the function/method;
}
1. Access specifier
3. Return-Type
It specifies the type of value that the return statement of the function returns. It
may be any valid Java data type. If no value is being returned, we use the return
type as void.
4. Function-name
The name of the function should be a valid Java identifier. The naming conventions
generally followed for method names are:
✔ It should be meaningful.
✔ It should begin with a lowercase letter. For names having multiple words, we use
the camelCase naming convention.
For example:
✔ printReportCard()
✔ getMarks()
• The method name should generally begin with a verb followed by one or more
nouns.
For example:
✔ readData
✔ findFile
✔ calculateInterestAmount
5. Parameter list
The body of the Java method should be enclosed within curly braces{} containing all
the code to perform operations and tasks .
static members
In Java, static members are those which belong to the class which can be accessed
without instantiating the class. The static keyword can be used with methods, fields,
classes (inner/nested), blocks.
Constructors
•Constructors are used to give initial values to the instance variables or to perform
any other start-up procedures.
Syntax:
class ClassName
{
ClassName()
{
// Initialization Statements;
}
}
• Parameterized Constructors
• These constructors the instance variables of a method will be initialized with fixed
values for all objects.
Example 1:
class MyClass {
int num;
MyClass() {
num = 100;
}
}
Output:
100 100
--------------------------------------------------------------------------------
Example 2:
Output:
Parameterized Constructors
Example 1:
class MyClass { int x;
MyClass(int i) { x = i;
}
}
public class ConsDemo {
public static void main(String args[]) { MyClass
t1 = new MyClass(10); MyClass t2 = new
MyClass(20);
System.out.println(t1.x + " " + t2.x);
}
}
Output:
10 20
---------------------------------------------------------------------------
Example 2:
class Student { int rollno; String name; String
city;
System.out.println(s1);
// compiler writes here s1.toString()
System.out.println(s2);
// compiler writes here s2.toString()
}
}
Output:
101 Raj Chennai
102 Vijay Pondy
-----------------------------------------------------------------------------
Constructor Overloading
//Constructor overloaded
Cricketer(String name, String team, int age)
{
this.name = name; this.team = team; this.age =
age;
}
Output:
-----------------------------------------------------------------------------
The this Keyword
A method will need to refer to the object that invoked it. To allow this, Java defines the
this keyword. this can be used inside any method to refer to the current object. That is,
this is always a reference to the object on which the method was invoked.
You can use this anywhere a reference to an object of the current class
Access Specifier / Access Modifier
•Access Modifier set access levels for classes, variables, methods and constructors.
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.
private : The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
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.
Outside Outside
Within Package
Access Within Package Package
(Both Sub Class and
Modifier Class (Sub Class (Non Sub
Non Sub Class)
Only) Class Only)
Private Yes No No No
Non-access modifiers
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 context. Final can be: variable, method and class.
5.transient - Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.
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.
Static Methods
static methods can be created using the keyword static. Static methods can access
only static fields and methods. To access static methods there is no need to
instantiate the class. Static methods can be accessed using just the class name.
The most common example of a static member is main( ). main( ) is declared as
static because it must be called before any objects exist.
When objects of its class are declared, no copy of a static variable is made. Instead,
all instances of the class share the same static variable.
if you wish to call a static method from outside its class, you can do so using the
following general form:
classname.method( )
Here, classname is the name of the class in which the static method is declared.
A static variable can be accessed in the same way—by use of the dot operator on the
name of the class.
Example 1:
class StaticDemo {
public static void sample() { System.out.println("Static
Method Demo is Success");
}
}
Student(int r, String n) {
rollno = r; name = n;
}
// method to display values void display() {
System.out.println(rollno + " " + name + " " +
college);
}
}
public class StaticMethodDemo {
public static void main(String args[]) {
// creating objects
Student s1 = new Student(4001, "AJAY");
Student s2 = new Student(4002, "AKASH");
s1.display();
s2.display();
System.out.println("After Static Method Call");
Student.change(); // calling change method
Student s3 = new Student(4003, "ARUN");
s1.display();
s2.display();
s3.display();
}
}
Output:
4001 AJAY R.M.K. College
4002 AKASH R.M.K. College
After Static Method Call
-----------------------------------------------------------------------------
Static Fields
Static field can be created by using the keyword static. The static fields have the
same value in all the instances of the class. These are created and initialized when
the class is loaded for the first time. Static fields can be accessed using the class
name (without instantiation).
Example 1:
class StatFieldDemo {
public static int data = 20;
}
Output:
Value of Static Data is 20 Static Field Demo is Success
-----------------------------------------------------------------------------
Example 2:
class Student {
int rollno; // Instance variable String name;
// Static variable
static String college = "R.M.K. College";
// Constructor
Student(int rollno, String name) {
this.rollno = rollno;
this.name = name;
}
// Method to display the values void display() {
System.out.println(rollno + " " + name + " " +
college);
}
}
Output:
4001 AJAY R.M.K. College
4002 AKASH R.M.K. College
After Changing Static Field
4001 AJAY R.M.K. Engineering College 4002 AKASH
R.M.K. Engineering College 4003 ARUN R.M.K.
Engineering College
----------------------------------------------------------------------------
Final
A field can be declared as final. Doing so prevents its contents from being modified,
making it, essentially, a constant. This means that you must initialize a final field
when it is declared. There are two ways to do this:
Example:
In addition to fields, both method parameters and local variables can be declared
final. Declaring a parameter final prevents it from being changed within the method.
Declaring a local variable final prevents it from being assigned a value more than
once.
The keyword final can also be applied to methods, but its meaning is substantially
different than when it is applied to variables
Comments
• Comments are the statements that are not executed by the compiler
and interpreter.
Types of Comments
• Documentation Comment
Syntax:
Example:
public class JavaCommentsDemo {
Output:
10
----------------------------------------------------------------------------
▪ Java Multi Line Comment
Syntax:
/* This is
multi line
comment
*/
Example:
public class JavaCommentsDemo {
}
}
Output:
10
----------------------------------------------------------------------------
Predict the output of the following code
1.class Test {
public static void main(String [ ] ar) { byte b=128;
System.out.println(b);
2.class Test {
boolean b=1;
System.out.println(f); System.out.println(b);
3.class Test {
4.class Test {
public static void main(String [ ] ar) { int
a=10,b=017,c=0X3A;
System.out.println(a+","+b+","+c);
}
5. class Test {
9A=10; System.out.println(9A);
6. class Test {
x; System.out.println(x);
1.class Sample{
boolean b = true;
if(b){
else {
} } }
2.class Sample {
public static void main(String[] args) {
while(false)
System.out.println("while loop");
} }
3.class Sample {
public static void main(String[] args) {
for( ; ; )
System.out.println("For loop");
}
Good Programming Practice
if statement
Always use {} for if statements Avoid the following error prone if (condition)
//ERROR
statement;
switch-case statement
int width;
is preferred over int height,width;
Do not put different types on the same line int height,width[]; //WRONG
The main method of the EBMain Class may look like this:
public static void main(String a[])
{
float slab[ ] = { 2.3f, 4.2f, 5.5f };
System.out.println(new Connection(130,100,slab ).ComputeBill());
}
11. Part A Question & Answers
1. Give some characteristics of procedure-oriented language. (K2,CO1)
The characteristics of procedure-oriented language are,
❖ Emphasis is on doing things(algorithms).
❖ Larger programs are divided into smaller programs known as functions.
❖ Most of the functions share global data.
❖ Data move openly around the system from function to function.
❖ It employs top-down approach in program design.
2. 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.
3. 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.
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.
14. 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.
24. 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;
}
Part A Question & Answers
Example:
public class Dog
{
String breed; int age;
String color; void barking()
{
}
void hungry()
{
}
void sleeping()
{
}
}
25. 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
26. 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.
Part A Question & Answers
27. 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.
31. 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.
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).
}
// constructor used when no dimensions specified Box()
{
width = height = depth = 0;
}
// constructor used when cube is created Box(double len)
{
width = height = depth = len;
}
34. What is method in Java? Give its Benefit. (K1, CO1)
Method is a collection of statements that perform some specific task and return the
result to the caller. A method can perform some specific task without returning
anything. Methods allow us to reuse the code without retyping the code. In Java,
every method must be part of some class.
Part A Question & Answers
35. 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 has six components :
Access specifier Modifier
Return-Type Method_name Parameter list Method Body
36. Write a code snippet to illustrate method is declared in Java. (K2, CO1)
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
37. 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.
Part A Question & Answers
38. Write a simple program illustrate usage of method in Java. (K2, CO1)
public class methodDemo
{
public static void myMethod()
Output:
{ System.out.println("My Function called"); About to encounter a method. My
} Function called
public static void main(String[] args)
Method was executed successfully!
{
System.out.println("About to encounter a method."); myMethod(); // method call
39. 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.
40. 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. */ classHelloWorld
{
public static void main(String[] args)
{
// Next statement is print – This is single line comment. System.out.println("Hello,
World!");
}
}
Part A Question & Answers
41. 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.
42. 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.
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)
i. Default constructors
ii. Parameterized constructor
iii. Overloaded constructors
iv. A call to another constructor with this operator
v. An object initialization block
vi. A static initialization block
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)
Part B Questions
19. Assess the different methods in java.Util. Arrays class with example (K5, CO1)
20. Create a Java program for push and pop operations in stack usingarrays in classes
and object. (K5, CO1)
21. Make a class Student. The Student class has data members such a sroll number,
name,
22. 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)
23. 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)
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.
16. Assessment Schedule
• Tentative schedule for the Assessment During
2021-2022 odd semester
Name of the
S.NO Start Date End Date Portion
Assessment
114
17. Text Books & References
TEXT BOOKS
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”, 9th 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”, Dreamtech press, 2011.
4.Timothy Budd, “Understanding Object-oriented programming with Java”, Updated
Edition, Pearson Education, 2008.
5.https://www.tutorialspoint.com/java/index.htm
6.https://www.javatpoint.com/java-tutorial
7.https://www.w3schools.com/java/
8.https://www.geeksforgeeks.org/java-tutorial/
9.https://docs.oracle.com/javase/tutorial/
18. Mini Project
Interest Calculator
Calculate interest based on the type of the account and the status
of the account holder. The rates of interest changes according to
the amount (greater than or less than 1 crore), age of account
holder (General or Senior citizen) and number of days if the type
of account is FD or RD.
Some sample rates are given in the below tables: Rate of FD
citizen) and interest for amounts below 1 Crore:
Normal 4%
NRI 6%
Requirements:
1. Separate classes should be created for the different types of
accounts.
2. All classes should be derives from an abstract class named
‘Account’ which contains a method called ‘calculateInterest’.
3. Implement the calculateInterest method according to the type of
the account, interest rates, amount and age of the account holder.
4. If the user is entering any invalid value (For eg. Negative value) in
any fields, raise a user defined exception.
Sample class structure is given below:
Account(Abstract)
double interestRate
double amount
FDAccount
double interestRate
double amount
int noOfDays
ageOfACHolder
abstract double calculateInterest()
SBAccount
double interestRate
double amount
abstract double calculateInterest()
RDAccount
double interestRate
double amount
int noOfMonths;
double
monthlyAmount;
abstract double calculateInterest()
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.