0% found this document useful (0 votes)
16 views

3 Mech - Java Programming Unit 1

Uploaded by

mokkapunai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

3 Mech - Java Programming Unit 1

Uploaded by

mokkapunai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

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

Department : Mechanical Engineering

Batch / Year :2021-2025 / II Year

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

6 CO- PO/PSO Mapping 10

7 Lecture Plan 11

8 Activity based learning 12

9 Lecture Notes 14

10 Assignments 96

11 Part A Questions & Answers 98

12 Part B Questions 108

13 Supportive online Certification courses 110

14 Real time Applications 111

15 Contents beyond the Syllabus 112

16 Assessment Schedule 113

17 Prescribed Text Books & Reference Books 114

18 Mini Project Suggestions 115

5
2. COURSE OBJECTIVES

• To understand Object Oriented Programming concepts and


fundamentals of Java
• To know the principles of packages, inheritance and
interfaces
• To define exceptions and multithreading
• To develop a java application with I/O streams and generics
classes
• To use the functionalities of Strings and Collections

6
3. PRE REQUISITES

Pre-requisite Chart

20CS302 – OBJECT ORIENTED


PROGRAMMING

20GE101 – PROBLEM SOLVING AND C


PROGRAMMING

7
4. SYLLABUS

20CS304 JAVA PROGRAMMING LTPC3003


OBJECTIVES:
To understand Object Oriented Programming concepts and fundamentals of Java
To know the principles of packages, inheritance and interfaces
To define exceptions and multithreading
To develop a java application with I/O streams and generics classes
To use the functionalities of Strings and Collections
UNIT I : INTRODUCTION TO OOP AND JAVA FUNDAMENTALS 9
An Overview of Java - Data Types, Variables, and Arrays – Operators – Control
Statements – Class Fundamentals – Declaring objects – Methods – Constructors – this keyword -
Overloading methods - Overloading constructors - Access Control – Static – Final.
UNIT II - INHERITANCE, PACKAGE AND INTERFACES 9
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
UNIT III - MULTITHREADING, I/O AND GENERIC PROGRAMMING 9
Exception Handling: Exception-Handling Fundamentals, Exception Types, Uncaught
Exceptions, Using try and catch, Multiple catch Clauses, Nested try Statements, throw, throws,
finally, Java’s Built-in Exceptions. Multithreaded Programming: Thread Creation
UNIT IV I/O AND GENERIC PROGRAMMING 9
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.
UNIT V STRING HANDLING AND COLLECTIONS 9
String Handling – Collections: The Collection Interfaces, The Collection Classes –
List, Array List, Set, Iterator – Map.
TOTAL: 45 PERIODS

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

COURSE OUTCOMES HKL


Understand the Object Oriented Programming concepts and
CO1 K2
fundamentals of Java

Develop Java programs with the packages, inheritance and


CO2 K3
interfaces

CO3 Build applications using Exceptions and Threads. K3

CO4 Build Java applications with I/O streams and generics classes K3

CO5 Use Strings and Collections in applications K3


6. CO-PO/PSO Mapping

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

S. Scheduled Actual Date Mode of Taxonomy


Topic CO
No. Date of Completion Delivery Level
Overview of Java, Data Video/
20.08.2021 CO1
1 Types PPT K1
PPT/
Variables and Arrays 21.08.2021 CO1 K1
2 Demo
PPT/
Operators 23.08.2021 CO1 K1
3 Demo
PPT/
4 Control statements 24.08.2021 CO1 K1
Demo
Class fundamentals, PPT/
25.08.2021
5 Declaring Objects, Methods CO1 Demo K2

PPT/
Constructors, this keyword 27.08.2021
6 CO1 Demo K2

Overloading Methods, PPT/


28.08.2021
7 Overloading Constructors CO1 Demo K3

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

Activity Based Online Test Unit 1 through Hackerrank

https://hr.gs/oopstest1
Overview of JAVA

Object Oriented Programming Vs Procedural Programming

Object Oriented Programming Procedural Programming

1. Basic building blocks are object and 1. Basic building blocks are function
its object centric and its algorithm centric

2. Bottom up approach 2. Top down approach

3. Easy to modify 3. Complex code

Object Oriented Programming Procedural Programming


4. Objects communicate with each other 4. Functions communicate with each
via functions, so data seems to be more other via data, so data seems to be less
secure secure

Refer:
https://drive.google.com/file/d/1RjO6Q8PHd9hTkY3Uogz4eVc35UHIO224/view?usp=
sharing
Object Oriented Programming

Object Oriented Programming is a Methodology or Paradigm to design a


Program/Software application based on objects. Objects are real-world entity.
Any things we see, that could be differentiated from another is called object. Objects
should have a well defined boundary.

Refer: https://www.youtube.com/watch?v=qwS-BCOCB-A

Characteristics of Object Oriented Programming

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:

•State: It is represented by attributes of an object. It also reflects the properties of


an object.

•Behavior: It is represented by methods of an object. It also reflects the response


of an object with other objects.
• Identity: It gives a unique name to an object and enables one object to interact
with other objects.

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 = 3


Color = Brown Size = Big

Breed = Bulldog
Age = 2
Color = Black Size = Medium

Objects interact with each other


to provide solutions to the real-
world problems through the
functions. For eg. in a railway
reservation application the objects
train and passenger interact with
each other through the
functionalities like booking a ticket,
cancelation of tickets, etc.
Properties Behavior
−Train No. −reserveticket()
−Train Name −cancelticket() Train
−No. of seat −checkavailability()

reserveticket()
Class

•A class is a blueprint or a template from which individual objects are created. A


class is a group of objects which have common properties. It represents the set of
properties or methods that are common to all objects of one type. It is a logical
entity. It can't be physical. A class can contain any of the following variable types.

•Local variables − Variables defined inside methods, constructors or blocks are


called local variables. The variable will be declared and initialized within the method
and the variable will be destroyed when the method has completed.

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

•Technically in encapsulation, the variables or data of a class is hidden from any


other class and can be accessed only through any member function of own class in
which they are declared.

•As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.

•Encapsulation can be achieved by declaring all the variables in the class as private

Inheritance

•Inheritance is the mechanism by which one object is allowed to derive the


properties (fields and methods) of another. The class whose features are inherited
is known as super class (or a base class or a parent class). The class that inherits
the other class is known as sub class (or a derived class, extended class, or child
class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.

•Inheritance supports reusability, i.e. when we want to add new features to an


existing entity, we can derive our new entity from the existing using inheritance.
This enables reusing the fields and methods of the existing class.

Types of Inheritance Multi-level Inheritance

Single Inheritance Class A

Class A
Class B

Class B
Class C
Hierarchical Inheritance Multiple Inheritance

Class A Class A Class B

Class B Class B Class C

Polymorphism

•Polymorphism is the ability of an object to take on many forms. Polymorphism is


a concept by which a single action can be performed by different ways. The most
common use of polymorphism in OOP occurs when a parent class reference is used
to refer to a child class object.

There are two types of polymorphism:

•Compile time polymorphism or Static Polymorphism or Static Binding or Early


Binding – implemented using method overloading

•Runtime polymorphism or Dynamic Polymorphism or Dynamic Binding or Late


Binding – implemented using method overriding

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.

•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

Characteristics or Features of Java Language

•Simple

• Easy to write and more readable and eye catching.

• 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

• Cannot harm other system thus making it secure.

• Provides a secure means of creating Internet applications.

• Provides secure way to access web applications.

•Portable
• Can execute in any environment for which there is a Java run-time system.
(JVM)

• Can be run on any platform (Linux,Window,Mac)

• Can be transferred over world wide web (e.g. applets)

•Object-oriented

• Java is object-oriented programming language.

• Like C++ java provides most of the object oriented features.

• Pure OOP Language. (while C++ is semi object oriented)


• Robust
• Encourages error-free programming by being strictly typed and performing
run-time checks.

• Multithreaded

• Provides integrated support for multithreaded programming.

• Architecture-neutral

• Java is not tied to a specific machine or operating system architecture.

• Machine Independent i.e Java is independent of hardware.

• Interpreted

• Supports cross-platform code through the use of Java bytecode.

• Bytecode can be interpreted on any platform by JVM.

• High performance

• Bytecodes are highly optimized.

• JVM can executed them much faster.

• Distributed

• Java was designed with the distributed environment.

• Java can transmit, run over internet.

• 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

• Type checking is strictly done is Java.


Solve the Puzzle to discover the given word
Java Environment/Java Architecture

Java programs can typically be developed in five stages:

1.Edit : Use an editor to type the source code (Welcome.java)

2.Compile: javac, the Java compiler is used to translate the source code to
machine independent, bytecode. Bytecodes are called .class file

3.Loading: Class loader loads the bytecodes from .class and other libraries file into
main memory.

4.Verify: Verifier make sure, whether the bytecodes are valid and do not violate
security restrictions

5.Execute: Java Virtual Machine (JVM) uses a combination of interpretation and


just-in-time compilation to translate bytecodes into machine language. Applications
are run on user's machine, i.e. executed by interpreter with java command (java
Welcome).
Take up the following Quiz

1.Write the correct order of the Java program execution

A. Class Loader

B. Interpretation

C. Compilation

D. Byte Code Verification

E. Java Source Code

F. Execution

2.Which of the following is used to load a .class file?

A. Class Loader

B. Byte Code Verifier

C. JIT Compiler

D. Interpreter

3.When a java program is compiled, it creates a

A. an obj file

B. an exe file

C. a .class file

D. a .sh file

4.The JDK is a superset of the JRE, and contains everything that is in the JRE, plus
tools such as the compilers and debuggers necessary for developing applets and
applications.

A. TRUE

B. FALSE
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

/*

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

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 similar
to a class in Java but it contains only constants and method
declarations.

Class Definition

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

The main method is from where the execution actually starts and follows the order
specified for the following statements. Structure of main method class

public class Example{


//main method declaration
public static void main(String args[]) System.out.println
("hello world");
}
}
public class Example: This creates a class called Example. You should make sure
that the class name starts with a capital letter, and the public word means it is
accessible from any other classes.

Braces: The curly brackets are used to group all the commands together. To make
sure that the commands belong to a class or a method.

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

String[] args: It is an array where each element is a string, which is named as


args. If you run the Java code through a console, you can pass the input parameter.
The main() takes it as an input.

System.out.println(); : The statement is used to print the output on the screen


where the system is a predefined class, out is an object of the PrintWriter class. The
method println prints the text on the screen with a new line. All Java statements end
with a semicolon.
Example Structure of Java Source File
/* A first program in Java */
public class Welcome
{
public static void main( String args[])
{
System.out.println( "Welcome to Java!" );
// Prints Welcome to Java!
}
}

Execution of Java Program


Java program can be executed using the following means
1.In command prompt
2.IDE
3.Online compilers
Command Prompt Execution
(Refer: https://www.youtube.com/watch?v=zBF1M8dTftk)
1.Download and Install JDK
(Refer: https://www.oracle.com/java/technologies/javase-downloads.html )
Installed in C:\Program Files\Java\JDK

2.Save the Source Code in any working space


Let Working Space be 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 Eg. Eclipse, JCreator, Code
Blocks, etc.

Refer: https://www.youtube.com/watch?v=4WwBvnH9KCA

1.Download and Install IDE(Eclipse) and JDK (Refer:

https://www.eclipse.org/downloads/)

2.Open a new Java Project using the IDE

3.Open a new class

4.Add main method

5.Compile and Run using menus

Online Compilers

Many online compilers are available for practicing Java program, which are simple to
use.

1. https://www.onlinegdb.com/online_java_compiler

2. https://www.tutorialspoint.com/compile_java_online.php

3. https://compiler.javatpoint.com/opr/online-java-compiler.jsp

4. https://www.jdoodle.com/online-java-compiler/

5. https://www.codechef.com/ide

Java Language Fundamentals

1.Keywords

2.Data Types

3.Variables

4.Operators

5.Conditional Statements

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

Keywords

Keywords have predefined meaning, which cannot be


used as identifier. Java Keywords are are given below

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 instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp volatile

const float native super while


Solve the word puzzle to find all the Keywords in Java

Predict the output of the following code

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

int for=2; System.out.println(for);


}
}
Data Types

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

There are two types of data types in Java:

• Primitive data types

• Non-Primitive data types

1. Primitive data types:

•These are the most basic data types available in Java Language.

•Primitive data types are the building blocks of data manipulation.

There are 8 types of primitive data types

Default
Data Size Maximum Range Value (for
Minimum Range
Type (in bits) fields)

byte 8 -128 +127 0

short 16 -32768 +32767 0

int 32 -2147483648 +2147483647 0

long 64 -9223372036854775808 +9223372036854775807 0L

float 32 1.40E-45 3.40282346638528860e+38 0.0f

double 64 4.94065645841246544e-324d 1.79769313486231570e+308d 0.0d

char 16 (UNICODE Representation) 0 to 65,535 '\u0000'

boolean 1 NA NA false
2. Non-Primitive data types:

In Java, non-primitive or reference data types, Stores address or references to


information.

•Non Primitive data type includes

• class

• interface

• String

• array

• etc.,

Difference between primitive and non-primitive data types are:

S.No. Primitive Data Types Non-Primitive Data Types

1 Non-Primitive types may be user


Primitive types are predefined in Java
defined

2 Non-Primitive types are reference or


Primitive type has always a value
address.

3 Primitive type cannot have null Non-Primitive type can have null

4 Size of a primitive type depends on the


Size of non-primitive is always same.
data type

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.

•Variable is a container which holds the value while the program is executed.

•Variable value can be changed during program execution

•Variable is assigned with a data type

•Variable is name of reserved area allocated in memory.


There are three types of variables in java: 1. local, 2. instance and 3. static.

1. Local Variable

•A variable declared inside the body of the method.

•It can be used only within that method

•It cannot be defined with "static" keyword.

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.

•It is not declared as static.

3. Static Variable

•A variable which is declared as static is called 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.

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

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

▪ The field's type.

▪ The field's name.

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

•Variable names are case-sensitive.

•A variable's name can be any legal identifier — an unlimited-length sequence of


Unicode letters and digits, beginning with a letter, the dollar sign "$", or the
underscore character "_".

•Subsequent characters may be letters, digits, dollar signs, or underscore


characters.

•White space is not permitted.

•keyword or reserved word should not be used as variable names.

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

Type Conversion and Casting

While assigning a value of one type to a variable of another type. If the two types are
compatible, then Java will perform the conversion automatically. Automatic type
conversion will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
Assign an int value to a byte variable. A byte is smaller than an int. This kind of
conversion is sometimes called a narrowing conversion. Remainder of the number
division 256 will be stored as byte.
A cast is simply an explicit type conversion. It has this general form:
(target-type) value;
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.

•Java array is an object.

•Java array can store only a fixed size set of elements.

▪ Cannot increase to accommodate more elements.

•Java array is index-based.

▪ First element of the array is stored at the 0th index.

▪ Second element is stored on 1st index and so on.

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.

Important point about Java arrays


•In Java all arrays are dynamically allocated.
•Since arrays are objects in Java, Size can be found using member length.
• A Java array variable can also be declared like other variables with [] after the
data type.

• The variables in the array are ordered and each has an index beginning 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.

• The direct super class of an array type is Object

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

▪ type declares the data type of the array

▪ var_name is the name of array

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

• When an array is declared, only a reference of array is created. Actual memory


allocation is done with help of new follows:
Syntax:

var_name = new type [size];

• var_name is the name of array


• new to allocate an array
• type specifies the type of data being allocated
• size specifies the number of elements in the array

Example:

int intArray[]; //declaring array

intArray = new int[20]; // allocating memory to array

or

int intArray [] = new int[20]; // combining both statements in one

•The elements in the array allocated by new, automatically initialized to zero


(for numeric types), false (for boolean), or null (for reference types).

Array Literal

When the size of the array and variables of array are already known, array
literals can be used.

int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; // Declaring


array literal

•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

•Each element in the array is accessed via its index.

•The index begins with 0 and ends at (total array size)-1.

•All the elements of array can be accessed using for Loop

for (int i = 0; i < arr.length; i++)

System.out.println("Element at index " + i + " : "+ arr[i]);


Java Program to illustrate the use of declaration, instantiation and
initialization of a array in a single line.

public class ArrayDemo {


public static void main(String args[]) {
// declaration, instantiation and
initialization
int[] a = new int[] { 33, 3, 4, 5 };
// int[] a = {33,3,4,5}; this is also
correct
// printing array
// length is the property of array for (int i = 0; i <
a.length; i++)
System.out.println(a[i]);
}
}

Output:

33
3
4
5

Two Dimensional Arrays

•Two Dimensional Array can be defined as an array of arrays.

•Two Dimensional array is organized as matrices

•Two Dimensional array can be represented as the collection of rows and columns.

Syntax:

array_name = new data_type[size1][size2];

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

• array_name: Name of the array

• size1, size2: Sizes of the dimensions respectively.


Example:

Two dimensional array:

int[][] twoD_arr = new int[3][4];

Three dimensional array:

int[][][] threeD_arr = new int[3][3][3];

2-D Array Declaration and Initialization

Syntax:

data_type[][] array_name = new data_type[x][y];

Example:

int[][] arr = new int[3][4];

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;

Two Dimensional Array Implementation


import java.util.Scanner; public class ArrayDemo {
public static void main(String[] args) { int[][] arr = new
int[3][3];
//Get the input from user
Scanner sc = new Scanner(System.in); for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++) { System.out.print("Enter Element
: ");
arr[i][j] = sc.nextInt(); System.out.println();
}
}
System.out.println("Printing Elements...");
for (int i = 0; i < 3; i++) {
System.out.println();
for (int j = 0; j < 3; j++) {
System.out.print(arr[i][j]
+ "\t");
}
}
}
}

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

The following table list arithmetic operators

Operator Description Example

+ Addition A+B

- Subtraction A-B

* Multiplication A*B

/ Division A/B

% Modulus A%B

/* Example to understand Arithmetic operator */


public class Sample {
public static void main(String[] args) { int a =
10;

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

Note: Division works in 3 different modes

i.Integer mode ( integer/integer, result is an integer)

ii.Real Mode ( integer/real or real/integer numbers, result is a real number)

iii.Mixed Mode ( real/real, result is a real number)

Unary Operators

The following are the unary operators

Operator Description Example

+ Unary plus operator +A

- Unary minus operator -A

++ Increment operator ++A or A++

-- Decrement operator --A or A--

++ and - - works in two different modes

•Pre increment/decrement – When it is part of a statement, increment/decrement


gets evaluated first, followed by the execution of the statement.

•Post increment/decrement – When the operator is part of a statement, the


statement gets processed first, followed by increment/decrement operation.
// Example for pre increment/decrement

public 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 = 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.

Operator Description Example

Two values are checked, and if equal, then the condition


== (A == B)
becomes true

Two values are checked to determine whether they are

!= equal or not, and if not equal, then the condition becomes (A != B)


true
Two values are checked and if the value on the left is

> 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 */

public class Sample {


public static void main(String[] args) { int a =
10;
int b = 20;
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("b >= a = " + (b >= a));
System.out.println("b <= a = " + (b <= a));
}
}

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.

Operator Description Example

This is known as Logical AND & it combines two


&& variables or expressions and if and only if both the (A && B) is false
operands are true, then it will return true
This is known as Logical OR & it combines two
|| variables or expressions and if either one is true or (A || B) is true
both the operands are true, then it will return true
Called Logical NOT Operator. It reverses the value of a
! !(A && B) is true
Boolean expression
/* Example to understand logical operator */
public class Sample {
public static void main(String[] args) { boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a && b));
System.out.println("a || b = " + (a || b));
System.out.println("!(a && b) = " + !(a &&
b));
}
}

Output:

a && b = false a || b = true


!(a && b) = true

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 AND &

• Bitwise OR |

• Bitwise EXOR ^

• Bitwise NOT ~ (unary operator)

• Shift Left <<

• Shift Right >>

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

int x = 7; int y = 9; 7-> 0111


9-> 1001
x & y = 1 0001

• 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; x 5|- >


y = 013
101
9-> 1001
1101
• Bitwise EXOR
The ^ operator compares two bits to check whether these bits are different. If they
are different, the result is 1.Otherwise, the result is 0. This operator is also
known as XOR operator.

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;

System.out.println("x & y = " + a);


System.out.println("x | y = " + b);
System.out.println("x ^ y = " + c);
}
}

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:

int x = 16; x = x >> 3;

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.

The result is 128.

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:

The original value of x is 8


After using << 2, the new value is 32
After using >> 4, the new value is 0

Predict the output of the following code snippets


1. public class Sample {
public static void main() {
int i_val = 10, j_val = 20; boolean chk;
chk = i_val < j_val; System.out.println("chk value: "+chk);
}}
2. class Test {
public static void main(String [ ] args) { int x=10;
int y=5;
System.out.println(++x+(++y));
}}

Flow Control
Control statements are statements which alter the normal execution flow of a
program. There are three types of Control Statements in java.

Selection statement Iteration Statement Jumping Statement

if while break continue


if – else for return
switch do – while

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:

If args[0] is 25 then the ouput is


Eligible to vote
Cascading if..else

Syntax:
if (condition-1) {
statement-1
}
….
else if(condition-n) {
statement-n
}
else {
default statement
}
next statement

/* program to print seasons for a month input using if & else if */


public class Sample {
public static void main(String[] args) {
int month = Integer.parseInt(args[0]);
if (month == 12 || month == 1 || month == 2)
System.out.println("Winter");
else if (month == 3 || month == 4 || month ==
5)
System.out.println("Spring");
else if (month == 6 || month == 7 || month ==
8)
System.out.println("Summer");
else if (month == 9 || month == 10 || month ==
11)
System.out.println("Autumn");
else
System.out.println("Invalid month");
}
}
Output:

If args[0] is 6 then the ouput is


Summer

switch case

The switch-case conditional construct is a more structured way of testing for


multiple conditions rather than resorting to a multiple if statement

Syntax:
switch (expression) { case value-1 : case-1 block break;

case value-2 : case-2 block break;

default : default block

break;

statement-x;
Note: expression must return an integral value Case value
must be an integral constant

/* This is an example of a switch case statement*/

public class Sample {


public static void main(String[] args) {
int weekday = Integer.parseInt(args[0]);
switch (weekday) {
case 1:
System.out.println("Sunday"); break;
case 2:
System.out.println("Monday"); break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday"); break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday"); break;
case 7:
System.out.println("Saturday"); break;
default:
System.out.println("Invalid
day");
}
}
}
Output:

If args[0] is 5 then the ouput is


Thursday
while Loop
It’s a entry controlled loop, the condition in the while loop is evaluated, and if the
condition is true, the code within the block is executed. This repeats until the
condition becomes false

Syntax:

while(condition) false
Boolean Condition
{
true
Body of the loop

} Body of the loop

/* This is an example for a while loop */


public class Sample {
public static void main(String[] args) { int i = 0;
while (i < 5) {
System.out.println("i: " + i); i = i + 1;
}
}
}
Output:

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

do{ Body of the loop

Body of the loop

} while(boolean expression); false


Boolean Condition

true

/* This is an example of a do-while loop */


public class Sample {
public static void main(String[] args) { int i = 5;
do {
System.out.println("i: " + i);
i = i + 1;
} while (i < 5);
}
}

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:

for(initialization; condition; increment/decrement) { Body of the

loop

/* This is an example of a for loop */


public class Sample {
public static void main(String[] args) { for (int i = 1; i <=
5; i++) {
System.out.println("i: " + i);
}
}
}

Output:

i: 1
i: 2
i: 3
i: 4
i: 5

Enhanced For Loop or For Each Loop


Enhanced for loop used along with a collection of data.
Syntax:
for(declaration : expression) {
Body of loop
}
/* This is an example of a enhanced for loop */
public class Sample {
public static void main(String[] args) {
int[] numbers = { 10, 20, 30, 40, 50 }; for (int i :
numbers) {
System.out.println("i: " + i);
}
}
}
Output:

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.

/* This is an example of a break statement */


public class Sample {
public static void main(String[] args) { for (int i = 1; i <=
5; i++) {
if (i == 2)
break;
System.out.println("i: " + i);
}
}
}

Output:

i: 1

continue Statement

•The continue statement skips the current iteration of a


loop.

•In while and do loops, continue causes the control to go


directly to the test- condition and then
continue the iteration process.

•In case of for loop, the increment section of the loop is


executed before the test- condition is evaluated.

/* This is an example of a continue loop */


public class Sample {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3, 4, 5 }; for
(int i : numbers) {
if (i == 3) {
continue;
}
System.out.println("i: " + i);
}
}
}

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.

•A class is a blueprint / template / prototype for creating objects.

•A class used to define user defined data-type.

•A class is a collection of data members (Fields) and member functions (Methods).

•A class is a logical grouping of data and functions.

•When a class is defined, no memory is allocated.

Declaring class in Java.

Every class in Java can be composed of the following elements:

• fields

• methods

• constructors
Syntax:

Access modifier class ClassName

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.

Example code to declare a class:


Class declarations can include these components, in order:

•Modifiers such as public, private, and a number of others.

•The class name, with the initial letter capitalized by convention.

•The name of the class's parent


(superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.

•A comma-separated list of interfaces implemented by the class, if any, preceded by


the keyword implements. A class can implement more than one interface.

•The class body, surrounded by braces, {}.

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

•An object is an instance of a class.

•When an object is instantiated / created memory is allocated.

•A software object maintains its state in variables and implements its behaviour with
methods.

•Objects are the building blocks of Object Oriented Programming

Using new keyword

The new keyword is used to create objects

Syntax:

ClassName objectName = new ClassName();


Example:

Employee empOne = new Employee(“Vijayakumar S”);

Object Creation has three parts

1.Declaration: Variable declarations that associate a variable name with an object


type.

2.Instantiation: The new keyword is a Java operator that creates the object.

3.Initialization: The new operator is followed by a call to a constructor, which


initialize the new object.
new operator dynamically allocates memory for an object.
class-var = new classname ( );
class-var is a variable of the class type being created. The classname is the name of
the class that is being instantiated. The class name followed by parentheses
specifies the constructor for the class. A constructor defines what occurs when an
object of a class is created.
Assigning Object Reference Variables
Employee e1 = new Employee();
Employee e2 = e1;
e1 and e2 will refer to the same object. The assignment of e1 to e2 did not allocate
any memory or copy any part of the original object. It simply makes e2 refer to the
same object as does e1.
Methods

A method is defined as a sequence of some declaration and execution statements.


These statements gather together to perform a specific task. A function or a method
must be defined before it is used anywhere in the program.

Syntax :
[access-specifier] [modifier] return-type function-name
([parameter list])
{
body of the function/method;
}

1. Access specifier

It can be public or protected or private or default. It is optional to use an access


specifier while defining a method.
2. Modifier

It can be static, final, synchronized, transient, and volatile. It is optional to use a


modifier

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 parameter list is a comma-separated list of variables of a function referred to as


arguments or parameters. A function may be without any parameters and in this
case, the parameter list is empty.
6. Method Body

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.

Example method definition:

Constructors

•Constructor initializes an object when it is created.

•Constructor has the same name as its class.

•Constructor is syntactically similar to a method.

•Constructors have no explicit return type.

•Constructors are used to give initial values to the instance variables or to perform
any other start-up procedures.

•All classes have constructors, whether programmer define one or not.

•Java automatically provides a default constructor that initializes all member


variables to default values.
• Once programmer defines own constructor, the system defined default
constructor is no longer used.

Syntax:
class ClassName
{
ClassName()
{
// Initialization Statements;
}
}

Java allows two types of constructors:

• No argument Constructors (Also called as Default Constructor)

• Parameterized Constructors

No Argument Constructors - User Defined Default Constructor

• No argument constructors of Java does not accept any parameters.

• Constructor which is defined in the class by the programmer is known as user-


defined default constructor.

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

public class ConsDemo {


public static void main(String args[]) { MyClass t1 =
new MyClass();
MyClass t2 = new MyClass(); System.out.println(t1.num
+ " " + t2.num);
}
}

Output:

100 100
--------------------------------------------------------------------------------
Example 2:

class Demo { Demo() { int a = 10; int b = 5; int c;


c = a + b;
System.out.println("User Defined Default Constructor");
System.out.println("Total of 10 + 5 = " + c);
}

public static void main(String args[]) { Demo obj =


new Demo();
}
}

Output:

User Defined Default Constructor Total of 10 + 5 = 15


-----------------------------------------------------------------------

Parameterized Constructors

•Constructor that accepts one or more parameters.

•Parameters are added in the same way as added to a method

•Declare them inside the parentheses after the constructor's name.

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;

Student(int rollno, String name, String city) {


this.rollno = rollno;
this.name = name; this.city = city;
}

//Overriding the toString() method public String


toString() {
return rollno + " " + name + " " + city;
}
}
public class ParameterizedConstructorDemo { public static
void main(String args[]) {
Student s1 = new Student(101, "Raj", "Chennai"); Student
s2 = new Student(102, "Vijay", "Pondy");

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

• Like methods, a constructor can also be overloaded.

• Overloaded constructors are differentiated based on their type of parameters or


number of parameters.

• Constructor overloading is not much different than method overloading.

• In case of method overloading program have multiple methods with same


name and different signature.

• Whereas in Constructor overloading program have multiple constructor with


same name and different signature.

• Only difference is that constructor have No return type.


Example:
class Cricketer { String name; String team;
int age;

Cricketer() // Default constructor


{
name = "";
team = ""; age = 0;
}

//Constructor overloaded
Cricketer(String name, String team, int age)
{
this.name = name; this.team = team; this.age =
age;
}

// Constructor object as Parameter


Cricketer(Cricketer ckt)
{
this.name = ckt.name; this.team = ckt.team;
this.age = ckt.age;
}
// Overriding the toString() method public
String toString()
{
return "This is " + name + " of " + team;
}
}
public class ConstructorOverloadingDemo {
public static void main(String[] args) { Cricketer c1 =
new Cricketer();
Cricketer c2 = new Cricketer("Sachin", "India", 32);
Cricketer c3 = new Cricketer(c2); System.out.println(c2);
// compiler writes here c2.toString()
System.out.println(c3);
// compiler writes here c3.toString() c1.name = "Virat";
c1.team = "India"; c1.age = 32; System.out.println(c1);

// compiler writes here c1.toString()


}
}

Output:

This is Sachin of India This is Sachin of India This is


Virat of India

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

•Java provides four Access Modifiers to set access levels

•Access Modifier set access levels for classes, variables, methods and constructors.

•The four access levels are

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.

public : The access level of a public modifier is everywhere. It can be accessed


from within the class, outside the class, within the package and outside the package.

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

Default Yes Yes No No

Protected Yes Yes Yes No

Public Yes Yes Yes Yes

Non-access modifiers

• Java has seven Non-Access Modifiers.

• Non-Access Modifiers are used with classes, methods, variables, constructors.

• Non-Access Modifiers are used to provide information to JVM.


Seven Non Access Modifiers are:

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

2.final - The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be: variable, method and class.

3.abstract - The abstract keyword is used to achieve abstraction in Java. It is a


non-access modifier which is used to create abstract class and method. The role of
an abstract class is to contain abstract methods

4.synchronized - Java programming language provides a very handy way of


creating threads and synchronizing their task by using synchronized blocks to keep
shared resources.

5.transient - Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.

6.volatile - Volatile keyword is used to modify the value of a variable (either


primitive type or objects) by different threads. It is also used to make classes thread
safe.

7.native - The native keyword is applied to a method to indicate that the method is
implemented in native code using JNI (Java Native Interface). Native is a modifier
applicable only for methods and cannot apply it anywhere else. The methods which
are implemented in C, C++ are called as native methods or foreign methods.

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.

Methods declared as static have several restrictions:


• They can only directly call other static methods of their class.
• They can only directly access static variables of their class.
• They cannot refer to this or super in any way.

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

public class StaticMethodDemo {


public static void main(String args[]) {
StaticDemo.sample();
}
}
Output:
Static Method Demo is Success
-----------------------------------------------------------------------------
Example 2:

class Student { int rollno; String name;


static String college = "R.M.K. College";

// static method to change the value of static variable


static void change() {
college = "R.M.K. Engineering College";
}

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

4001 AJAY R.M.K. Engineering College


4002 AKASH R.M.K. Engineering College
4003 ARUN R.M.K. Engineering College

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

public class StaticFieldDemo {


public static void main(String args[]) {
System.out.println("Value of Static Data is " +
StatFieldDemo.data);
System.out.println("Static Field Demo is Success");
}
}

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

public class StaticFieldDemo {


public static void main(String args[]) {
Student s1 = new Student(4001, "AJAY"); Student s2 =
new Student(4002, "AKASH"); s1.display();
s2.display();
// we can change the college of all objects by the
single line of code
Student.college = "R.M.K. Engineering College";
Student s3 = new Student(4003, "ARUN");
System.out.println("After Changing Static Field");
s1.display();
s2.display();
s3.display();
}
}

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:

You can give it a value when it is declared.


You can assign it a value within a constructor.
It is a common coding convention to choose all uppercase identifiers for final fields.

Example:

final int FILE_NEW = 1;


final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;

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.

• Comments can be used to provide information or explanation about the

variable, method, class or any statement.

•Comments can also be used to hide program code.

Types of Comments

There are three types of comments in Java.

• Single Line Comment

• Multi Line Comment

• Documentation Comment

▪Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

//This is single line comment

Example:
public class JavaCommentsDemo {

public static void main(String[] args) { int i = 10; //


Here, i is a variable System.out.println(i);
}
}

Output:
10

----------------------------------------------------------------------------
▪ Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:
/* This is
multi line
comment
*/

Example:
public class JavaCommentsDemo {

public static void main(String[] args) {


/*
Let's declare and print variable in java.
*/
int i = 10; System.out.println(i);

}
}

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 {

public static void main(String ar[]) { float f=1.2;

boolean b=1;

System.out.println(f); System.out.println(b);

3.class Test {

public static void main(String ar[]) {


double d=1.2D; System.out.println(d);

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 {

public static void main(String [ ] args) { int

9A=10; System.out.println(9A);

6. class Test {

public static void main(String [ ] args) { int

x; System.out.println(x);

• Match the following

DATA TYPES SIZE(bytes)


char 4
byte 2
int 1
double 8
Predict the output of the following codes

1.class Sample{

public static void main(String[]args) {

boolean b = true;

if(b){

System.out.println(" if block ");

else {

System.out.println(“ else block ");

} } }

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

Number per Line


One declaration per line is recommended int height;

int width;
is preferred over int height,width;

Do not put different types on the same line int height,width[]; //WRONG

Practice the following programs


1.Write a program to check whether a given year is leap or not
2.Write a program to check whether a given number is palindrome or not.
3.Write a program to check whether a given number is prime or not.
4.Write a program to evaluate the following series 1 + 4/x2 – 9/x3+ 16/x4 - … +
2n/xn
5.Write a program to print the pattern
*
* *
* * *
* * * *
6.Define a class Student with the data members Register number, Name, Age,
Department and Address. Write a function to find out average age of a class of
student by passing an array of student object as a parameter to that. Also pass
strength of the class as one of the parameter with a default value 66.
10. Assignment
Create a console based Java application that would allow an electricity board clerk to
compute the electricity bill amount that needs to be paid by the customer. The
following are the formulas that are to be used for computation of Bill for each type.

Unit Slabs Tariff Rate


First 50 units 2.3
Next 50 units 4.2
Remaining units 5.5

Class Method and Variables Description


Connection Class
int previousReading; Previous month meter reading
int currentReading; Current month meter reading
float[] slabs; Used to store different slab rate
public Connection(int currentReading, A constructor used to initialize
int previousReading,float slabs[]) the member variables
public float computeBill() An method to compute the bill for
a particular month
Getter and Setter methods for all the Getter and Setter methods for all
member variables member variables

Class Method and Variables Description


EBMain Main Class
public static void main(String[] args) Get the following input from the user
1.Get the previous month reading
2.Get the current month reading
3.After receiving all this data, invoke
the ComputeBill method of and test
your program

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.

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

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

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


Wrapping up of data and function within the structure is called as encapsulation.
The insulation of data from direct access by the program is called as data hiding
or information binding. The data is not accessible to the outside world and only
those functions, which are wrapped in the class, can access it.
Part A Question & Answers
6. What is meant by dynamic binding or late binding? (K3,CO1)
Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at the run-time.
7. Write the process of programming in an object-oriented language?
(K4,CO1)

The process of programming in an object-oriented language are,


❖ Create classes that define objects and their behavior.
❖ Creating objects from class definition.
❖ Establishing communication among objects.
8. List any four advantages of OOPS. (K2,CO1)
The advantages of OOPS are,
❖ The principle of data hiding helps the programmer to build secure programs
that cannot be invaded by code in other parts of the program.

❖ It is possible to have multiple instances of an object to co-exist without any


interference.
❖ Object oriented programming can be easily upgraded from small to large
systems.

❖ Software complexity can be easily managed.


9. Give any four applications of the OOPS. (K2,CO1)
The four applications of OOPS are,
❖ Real-time systems.
❖ Simulation and modeling.
❖ Object-oriented databases.
❖ AI and expert systems.
10.What are the features of Java? (K2,CO1)
The features of Java are,
❖ Simple.
❖ Object Oriented.
❖ Platform Independent.
❖ Robust.
❖ Multithreaded.
❖ Secure.
Part A Question & Answers
11. What is meant by virtual machine? (K2,CO1)
A Java virtual machine (JVM), an implementation of the Java Virtual Machine
Specification, interprets compiledJava binary code (called bytecode) for a
computer's processor (or "hardware platform") so that it can perform a Java
program's instructions

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


The two components of Java platform are, The Java Virtual Machine

The Java Application Programming Interface(API)


13. What is bytecode in Java? (K2,CO1)
Java bytecode is the form of instructions that the Java virtual machine
executes. Each bytecodeopcode is one byte in length, although some require
parameters, resulting in some multi-byte instructions. Not all of the possible 256
opcodes are used.

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.

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


The different types of access modifiers are,
❖ public: Any thing declared as public can be accessed from anywhere.
❖ private: Any thing declared as private can’t be seen outside of its class.
❖ protected: Any thing declared as protected can be accessed by classes in the
same package and subclasses in the other packages.

❖ default modifier: Can be accessed only to classes in the same package.


16. What is method overloading and method overriding? (K2,CO1)
Method overloading: When a method in a class having the same method name with
different arguments is said to be method overloading. Method overriding: When
a method in a class having the same method name with same arguments is
said to be method overriding.
Part A Question & Answers
17. List out the primitive types in Java. (K1,CO1)
The eight primitive types are listed:
boolean, char, byte, short, int, long, float and double

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


An array is a special object containing a group of contiguous memory locations that
have the same name and the same type and a separate variable containing an
integer constant equal to the number of array elements. The elements of Java
arrays are numbered starting from 0.

Example: double x []; // create an array reference


x = new double [5]; // create array object
19. Why Java use Unicode? (K2,CO1)
Java use Unicode to represent a character. Unicode defines a fully international
character set that can represent all of the characters found in all human
languages.

20. What is Classpath?(K2,CO1)


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

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


The Garbage collection is the process that is used to free the memory of the objects
that are no longer in use. When a program stops referencing an object, it is not
required any more and can be deleted. The space that is used by the object is
released for use by another object
Part A Question & Answers
22. Define Class. (K1, CO1)
Classes are basic concepts of Object Oriented Programming which revolve around the real life
entities.

❖ A class is a blueprint / template / prototype for creating objects.


❖ A class used to define user defined data-type.
❖ A class is a collection of data members (Fields) and member functions (Methods).
23. 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.

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.

28. Define final class. (K1, CO1)


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

29. Define static class. (K1, CO1)


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

30. Define inner Class. (K1, CO1)


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

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

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


Constructor overloading in Java is a technique of having more than one constructor
with different parameter lists. They are arranged in a way that each constructor
performs a different task. They are differentiated by the compiler by the number of
parameters in the list and their types
Part A Question & Answers
33. 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;
}
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

System.out.println("Method was executed successfully!");


}
}

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.

43. Differentiate constructor and method in Java. (K2, CO1)

S. No. Constructor Method


A Constructor is a block of code
A Method is a collection of statements which
1 that initializes a newly created
returns a value upon its execution.
object.

2 A Constructor can be used to A Method consists of Java code to be


initialize an object. executed.
3 A Constructor is invoked implicitly
A Method is invoked by the programmer.
by the system.
4 A Constructor is invoked when a
object is created A Method is invoked through method calls.
using the
keyword new.
5 A Constructor doesn’t have a
A Method must have a return type.
return type
6 A Constructor’s name must be
A Method’s name can be anything.
same as the name of the class.
12. 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)
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)

1. Write a Java program to Evaluate the following series 1-2+3- 4+…+n.


2. Write a Java program to test the prime numbers between the given two
limits(
24. Write a program to perform the following functions using classes, objects,
constructors and destructors where essential (K4, CO1)

i. Get as input the marks of 5students in 5 subjects


ii. Calculate the total and average
iii. Print the formatted result on the screen
13. Online Certifications
1. https://www.hackerrank.com/skills-verification/java_basic
2. https://www.sololearn.com/Course/Java/
3. https://www.coursera.org/specializations/object-oriented-programming
4. https://www.udemy.com/course/java-the-complete-java-developer-course/ [Paid]
5. https://nptel.ac.in/courses/106/105/106105191/ [Paid]
6. https://education.oracle.com/java-se-8-fundamentals/courP_3348 [Paid]
14. Real Time Applications in Day to
Day Life and to Industry
1. Artificial Intelligence Applications
2. Medical Applications
3. Scientific Applications
4. Mathematical Applications
15. Contents Beyond Syllabus
Command Line Arguments

When you execute a java program, you can pass command line arguments in the following
way :
java Simple <argument1> <argument2>….<argument-n>
You can access these arguments in your program, using the String array that you have
passed as an argument to the main method – String[] args
class Simple {
static public void main(String[] args) {
System.out.println(args[0]);
}
}
When we compile the above code successfully and execute it as Java Simple Hello, the
output will be Hello.
class Simple {
static public void main(String[] args) {
int i1 = Integer.parseInt(args[0]);
int i2 = Integer.parseInt(args[1]);
System.out.println(i1+i2);
}
}
When we compile the above code successfully and execute it as Java Simple 10 20, the
output will be 30.
class FindNumberOfArguments {
public static void main(String[ ] args) {
int len = args.length;
System.out.println(len);
}
}
If you compile the above code successfully and execute it as java FindLength A B C D E F,
the result will be 6.
16. Assessment Schedule
• Tentative schedule for the Assessment During
2021-2022 odd semester

Name of the
S.NO Start Date End Date Portion
Assessment

1 IAT 1 20.09.2021 25.09.2021 UNIT 1 & 2

2 IAT 2 22.10.2021 28.10.2021 UNIT 3 & 4

3 REVISION 13.11.2021 16.11.2021 UNIT 5 , 1 & 2

4 MODEL 18.11.2021 29.11.2021 ALL 5 UNITS

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:

Current Rates of interest


Maturity Period General Senior Citizen
7 days to 14 days 4.50 5.00

15 days to 29 days 4.75 5.25

30 days to 45 days 5.50 6.00

45 days to 60 days 7 7.50

61 days to 184 days 7.50 8.00

185 days to 1 year 8.00 8.50

Rate of FD interest for amounts above 1 Crore:

Maturity Period Interest Rate


7 days to 14 days 6.50
15 days to 29 days 6.75
30 days to 45 days 6.75
45 days to 60 days 8

61 days to 184 days 8.50

185 days to 1 year 10.00


Rate of RD interests:
Current Rates of interest
Maturity
General Senior Citizen
Period
6 months 7.50 8.00
9 months 7.75 8.25
12 months 8.00 8.50
15 months 8.25 8.75
18 months 8.50 9.00
21 months 8.75 9.25

SB Account interest rates:


Type of Account Interest Rate

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

Hint: Use method overriding


Sample Output:
Select the option:

1.Interest Calculator –SB


2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit
1

Enter the Average amount in your account: 10000


Interest gained: Rs. 400 Select the option:
1.Interest Calculator –SB
2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit
2

Enter the FD amount: 10000

Enter the number of days: 91

Enter your age: 65


Interest gained is: 800 Select the option:

1.Interest Calculator –SB


2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit

Enter the FD amount: 10000

Enter the number of days: 91

Enter your age: 34

Interest gained is: 750


Select the option:

1. Interest Calculator –SB


2. Interest Calculator –FD
3. Interest Calculator –RD
4. Exit

Enter the FD amount: 10000

Enter the number of days: -7

Enter your age: 78

Invalid Number of days. Please enter correct values.


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.

You might also like