Java Unit-i Course Plan
Java Unit-i Course Plan
Course Plan
Name of the Course: Object Oriented Programming Through Java (CS303PC)
Course Outcomes:
1. Demonstrate the behavior of programs involving the basic programmingconstructslikecontrol
structures, constructors, string handling and garbage collection.
2. Demonstrate the implementation of inheritance (multilevel, hierarchical and multiple) by
using extend and implement keywords
3. Use multithreading concepts to develop interprocess communication.
4. Understand the process of graphical user interface design and implementation using AWT or
swings.
5. Develop applets that interact abundantly with the client environment and deploy on the server.
UNIT-I
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts, coping
with complexity, abstraction mechanisms. History of Java, Java buzzwords, data types, variables, scope
and lifetime of variables, arrays, operators, expressions, control statements, type conversion and casting,
simple java program, concepts of classes, objects, constructors, methods, accesscontrol, this keyword,
garbage collection, overloading methods and constructors, parameter passing, recursion, nested and
inner classes, exploring String class.
UNIT-II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass, subtype,
substitutability, forms of inheritance specialization, specification, construction, extension, limitation,
combination, benefits of inheritance, costs of inheritance. Member access rules, super keyword uses,
using final keyword with inheritance, polymorphism- method overriding, abstract classes, the Object
class. Defining, Creating and Accessing a Package, Understanding CLASSPATH, importing packages,
differences between classes and interfaces, defining an interface, implementing interface, applying
interfaces, variables in interface and extending interfaces.
UNIT-III
Exception handling and Multithreading-- Concepts of exception handling, benefits of exception
handling, Termination or resumptive models, exception hierarchy, usage of try, catch, throw, throws
and finally, built in exceptions, creating own exception subclasses. Differences betweenmultithreading
and multitasking, thread life cycle, creating threads, thread priorities, synchronizing threads, inter thread
communication, thread groups, daemon threads.
UNIT-IV
ExploringStringclass,Objectclass,[Link],[Link]
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event model,
handling mouse and keyboard events, Adapter classes. graphics, layout manager – layout manager
types–border,grid,flow,cardandgridbag.
UNIT-V
Swing–Introduction, limitations of AWT, MVC architecture, components, containers, exploring
swing- JFrame and JComponent, JLabel, ImageIcon, JTextField, JButton, JCheckBox, JRadioButton,
JList, JComboBox, Tabbed Panes, Scroll Panes, Trees, and Tables. Menu Basics, Menu related classes
- JMenuBar,JMenu,JMenuItem,JCheckBoxMenuItem,JRadioButtonMenuItem,[Link]
popup menu
TEXTBOOKS:
1. Javathecompletereference,13thedition,Herbertschildt,[Link],McGrawHill.
2. UnderstandingOOPwithJava,updatededition,[Link],Pearsoneducation.
REFERENCEBOOKS:
1. AnIntroductiontoprogrammingandOOdesignusingJava,[Link],John Wiley &
sons.
2. AnIntroductiontoOOP,thirdedition,[Link],Pearsoneducation.
3. IntroductiontoJavaprogramming,[Link],Pearsoneducation.
4. AnintroductiontoJavaprogrammingandobject-orientedapplicationdevelopment,R.A. Johnson-
Thomson.
5. CoreJava2,Vol1,Fundamentals,[Link],eighthEdition, Pearson
Education.
6. Core Java 2, Vol 2, Advanced Features, Cay.S. Horstmann and Gary Cornell, eighth Edition,
Pearson Education
7. ObjectOrientedProgrammingwithJava,[Link],[Link],[Link],TMH.
8. JavaandObjectOrientation,anintroduction,JohnHunt,secondedition,Springer.
9. Maurach’sBeginningJava2JDK5,SPD.
1.1 Core Concepts
Why to learn Java?
Architectural & Core Benefits
Designing server-side
Spring Boot, REST
Backend Engineer logic and database
APIs, Hibernate
schemas.
Creating mobile
Java, Kotlin, Android
Android Developer applications for the
SDK
Android ecosystem.
Processing massive
Hadoop, Apache Spark,
Big Data Engineer datasets and building
Kafka
data pipelines.
Frameworks Spring Boot, Spring Security, Spring Data JPA, Microservices Architecture
Building robust
Salesforce, SAP,
SaaS / CRM enterprise-level
Oracle
software.
Client-side digital
Accenture, Deloitte,
Consulting transformation
TCS, Infosys
projects.
UNIT-I
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts,
coping with complexity, abstraction mechanisms. A way of viewing world – Agents, responsibility,
messages, methods, History of Java, Java buzzwords, data types, variables, scope and lifetime of
variables, arrays, operators, expressions, control statements, type conversion and casting,
simple java program, concepts of classes, objects, constructors, methods, access control, this
keyword, garbage collection, overloading methods and constructors, method binding, inheritance,
overriding and exceptions, parameter passing, recursion, nested and inner classes, exploring
string class.
OBJECT ORIENTED THINKING
When computers were first invented, programming was done manually by toggling in a binary
machine instructions by use of front panel.
As programs began to grow, high level languages were introduced that gives the programmer more
tools to handle complexity.
The first widespread high level language is FORTRAN. Which gave birth to structured
programming in 1960’s. The Main problem with the high level language was they have no
specific structure and programs becomes larger, the problem of complexity also increases.
So C became the popular structured oriented language to solve all the above problems.
However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s a
new way of programming was invented and it was OOP. OOP is a programming methodology
that helps to organize complex programs through the use of inheritance, encapsulation &
polymorphism.
NEED FOR OOP PARADIGM
Traditionally, the structured programming techniques were used earlier.
There were many problems because of the use of structured programming technique.
The structured programming made use of a top-down approach.
To overcome these problems the object oriented programming concept was created.
The object oriented programming makes use of bottom-up approach.
It also manages the increasing complexity.
The description of an object-oriented program can be given as, a data that controls access to code.
The object-oriented programming technique builds a program using the objects along with a
set of well-defined interfaces to that object.
The object-oriented programming technique is a paradigm, as it describes the way in which
elements within a computer program must be organized.
It also describes how those elements should interact with each other.
In OOP, data and the functionality are combined into a single entity called an object.
Classes as well as objects carry specific functionality in order to perform operations and to achieve
the desired result.
The data and procedures are loosely coupled in procedural paradigm.
Whereas in OOP paradigm, the data and methods are tightly coupled to form objects.
These objects helps to build structure models of the problem domain and enables to get effective
solutions.
OOP uses various principles (or) concepts such as abstraction, inheritance, encapsulation and
polymorphism. With the help of abstraction, the implementation is hidden and the functionality is
exposed.
Use of inheritance can eliminate redundant code in a program. Encapsulation enables the data and
methods to wrap into a single entity. Polymorphism enables the reuse of both code and design.
SUMMARY OF OOP CONCEPTS
Everything is an object.
Computation is performed by objects communicating with each other, requesting that other objects
perform actions. Objects communicate by sending & receiving messages. A message is a request for
an action bundled with whatever arguments may be necessary to complete the task.
Each object has its own memory, which consists of other objects.
Every Object is an instance of class. A class simply represents a grouping of similar objects, such as
integers or lists.
The class is the repository for behavior associated with an object. That is all objects that are
instances of same class can perform the same actions.
Classes are organized into a singly rooted tree structure, called inheritance hierarchy.
OOP CONCEPTS
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every
program is follows the concept of object. In other words, OOP is a way of writing programs based on
the object concept.
The object-oriented programming paradigm has the following core concepts.
Class
Object
Encapsulation
Inheritance
Polymorphism
Abstraction
Class
Class is a blue print which is containing only list of variables and methods and no memory is allocated
for them. A class is a group of objects that has common properties.
Object
Any entity that has state and behavior is known as an object.
For example a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can
be defined as an instance of a class.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Encapsulation
Encapsulation is the process of combining data and code into a single unit.
In OOP, every object is associated with its data and code.
In programming, data is defined as variables and code is defined as methods.
The java programming language uses the class concept to implement encapsulation.
Inheritance
Inheritance is the process of acquiring properties and behaviors from one object to another
object or one class to another class.
In inheritance, we derive a new class from the existing class. Here, the new class acquires the
properties and behaviors from the existing class.
In the inheritance concept, the class which provides properties is called as parent class and the
class which recieves the properties is called as child class.
Person
name,
designation
learn(),
walk(),
eat()
Polymorphism
Polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviors.
The java uses method overloading and method overriding to implement polymorphism.
Method overloading - multiple methods with same name but different parameters.
Method overriding - multiple methods with same name and same parameters.
Abstraction
Abstraction is hiding the internal details and showing only essential functionality.
In the abstraction concept, we do not show the actual implementation to the end user, instead
we provide only essential things.
For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system
works? etc.
COPING WITH COMPLEXITY
Coping with complexity in Java, or any programming language, is an essential skill for software
developers.
As your Java projects grow in size and complexity, maintaining, debugging, and extending your
code can become challenging.
Here are some strategies to help you cope with complexity in Java:
1. Modularization: Breaking down the code into smaller, self-contained modules, classes, or
packages to manage complexity. Each module should have a specific responsibility and interact
with others through well-defined interfaces.
2. Design Patterns: Using established design patterns to solve common architectural and design
problems. Design patterns provide proven solutions to recurring challenges in software
development.
3. Encapsulation: Restricting access to class members using access modifiers (public, private, protected)
to hide implementation details and provide a clear API for interacting with the class.
4. Abstraction: Creating abstract classes and interfaces to define contracts that classes must adhere
to, making it easier to work with different implementations.
5. Documentation: Writing comprehensive documentation, including code comments and Javadoc, to
explain how the code works, its purpose, and how to use it.
6. Testing: Implementing unit tests to ensure that individual components of the code function
correctly, which helps identify and prevent bugs.
7. Code Reviews: Collaborating with team members to review and provide feedback on code to catch
issues and ensure code quality.
8. Version Control: Using version control systems like Git to manage changes, track history, and
collaborate with others effectively.
9. Refactoring: Regularly improving and simplifying the codebase by removing redundancy and
improving its structure.
ABSTRACTION MECHANISM
In Java, abstraction is a fundamental concept in object-oriented programming that allows you to
hide complex implementation details while exposing a simplified and well-defined interface.
Abstraction mechanisms in Java include the use of abstract classes and interfaces.
A WAY OF VIEWING WORLD
A way of viewing the world is an idea to illustrate the object-oriented programming concept with
an example of a real-world situation.
Let us consider a situation, I am at my office and I wish to get food to my family members who are
at my home from a hotel. Because of the distance from my office to home, there is no possibility of
getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them the
variety and quantity of food and the hotel name from which I wish to delever the food to my family
members.
AGENTS AND COMMUNITIES
Let us consider a situation, I am at my office and I wish to get food to my family members who are at
my home from a hotel. Because of the distance from my office to home, there is no possibility of getting
food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them the
variety and quantity of food and the hotel name from which I wish to delever the food to my family
members. An object-oriented program is structured as a community of interacting agents, called
objects. Where each object provides a service (data and methods) that is used by other
members of the community.
In our example, the online food delivery system is a community in which the agents are zomato and
set of hotels. Each hotel provides a variety of services that can be used by other members like zomato,
myself, and my family in the community.
RESPONSIBILITIES
In object-oriented programming, behaviors of an object described in terms of responsibilities.
In our example, my request for action indicates only the desired outcome (food delivered to my
family). The agent (zomato) free to use any technique that solves my problem. By discussing a problem in
terms of responsibilities increases the level of abstraction. This enables more independence between
the objects in solving complex problems.
MESSAGES & METHODS
To solve my problem, I started with a request to the agent zomato, which led to still more requestes among
the members of the community until my request has done. Here, the members of a community interact
with one another by making requests until the problem has satisfied.
-9223372036854775808 to
long 8 bytes 0L
+9223372036854775807
Float Data Types
Float data types are represent numbers with decimal point.
Minimum and Maximum
Data Type Memory Size Default Value
values
-3.4e38 to -1.4e-45 and 1.4e-45
float 4 byte 0.0f
to 3.4e38
-1.8e308 to -4.9e-324 and 4.9e-
double 8 bytes 0.0d
324 to 1.8e308
Note: Float data type can represent up to 7 digits accurately after decimal point.
Double data type can represent up to 15 digits accurately after decimal point.
Character Data Type
Character data type are represents a single character like a, P, &, *,..etc.
Minimum and Maximum
Default Value
Data Type Memory Size values
Local Variables
Variables declared inside the methods or constructors or blocks are called as local variables.
The scope of local variables is within that particular method or constructor or block in which they
have been declared.
Local variables are allocated memory when the method or constructor or block in which they are
declared is invoked and memory is released after that particular method or constructor or block is
executed.
Access modifiers cannot be assigned to local variables.
It can’t be defined by a static keyword.
Local variables can be accessed directly with their name.
Program
class LocalVariables
{
public void show()
{
int a = 10;
[Link]("Inside show method, a = " + a);
}
public void display()
{
int b = 20;
[Link]("Inside display method, b = " + b);
//[Link]("Inside display method, a = " + a); // error
}
public static void main(String args[])
{
LocalVariables obj = new LocalVariables();
[Link]();
[Link]();
}
}
Instance Variables:
Variables declared outside the methods or constructors or blocks but inside the class are called
as instance variables.
The scope of instance variables is inside the class and therefore all methods, constructors and
blocks can access them.
Instance variables are allocated memory during object creation and memory is released during
object destruction. If no object is created, then no memory is allocated.
For each object, a separate copy of instance variable is created.
Heap memory is allocated for storing instance variables.
Access modifiers can be assigned to instance variables.
It is the responsibility of the JVM to assign default value to the instance variables as per the type of
Variable.
Instance variables can be called directly inside the instance area.
Instance variables cannot be called directly inside the static area and necessarily requires an object
reference for calling them.
Program
class InstanceVariable
{
int x = 100;
public void show()
{
[Link]("Inside show method, x = " + x);
x = x + 100;
}
public void display()
{
[Link]("Inside display method, x = " + x);
}
public static void main(String args[])
{
ClassVariables obj = new ClassVariables();
[Link]();
[Link]();
}
}
Static variables
}
}
ARRAYS
An array is a collection of similar data values with a single name.
An array can also be defined as, a special type of variable that holds multiple values of the same
data type at a time.
In java, arrays are objects and they are created dynamically using new operator.
Every array in java is organized using index values.
The index value of an array starts with '0' and ends with 'zise-1'.
We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
One Dimensional Array
Multi Dimensional Array
One Dimensional Array
In the java programming language, an array must be created using new operator and with a specific
size. The size must be an integer value but not a byte, short, or long. We use the following syntax to
create an array.
Syntax
data_type array_name[ ] = new data_type[size];
(or)
data_type[ ] array_name = new data_type[size];
Example
class Onedarray
{
public static void main(String args[])
{
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<5;i++)
[Link](a[i]);
}
}
In java, an array can also be initialized at the time of its declaration.
When an array is initialized at the time of its declaration, it need not specify the size of the array
and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Example
int list[ ] = {10, 20, 30, 40, 50};
Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays.
To create a multidimensional array variable, specify each additional index using another set of
square brackets.
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
When an array is initialized at the time of declaration, it need not specify the size of the array and
use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Example
class Twodarray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
[Link](arr[i][j]+" ");
}
[Link]();
}
}
}
OPERATORS
An operator is a symbol that performs an operation. An operator acts on some variables called
operands to get the desired result.
Example: a+b
Here a, b are operands and + is operator.
Types of Operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
7. Bit wise operators
1. Arithmetic Operators: Arithmetic Operators are used for mathematical calculations.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
Operator Description
== Equal to
!= Not equal to
2. Logical OR ( || ) : Logical OR is denoted by double pipe characters (||). it is used to check the
combinations of more than one conditions. if any one condition true the complete condition becomes
true.
Truth table of Logical OR
Condition1 Condition2 Condition1 && Condition2
True True True
True False True
False True True
False False False
3. Logician NOT (!): Logical NOT is denoted by exclamatory characters (!), it is used to check the
opposite result of any given test condition. i.e, it makes a true condition false and false condition true.
Truth table of Logical NOT
Condition1 !Condition2
True False
False True
Bitwise operators are used for manipulating a data at the bit level, also called as bit level
programming. Bit-level programming mainly consists of 0 and 1.
They are used in numerical Computations to make the calculation process faster.
The bitwise logical operators work on the data bit by bit.
Starting from the least significant bit, i.e. LSB bit which is the rightmost bit, working towards the
MSB (Most Significant Bit) which is the leftmost bit.
A list of Bitwise operators as follows…
Operator Meaning
0 0 0
0 1 0
1 0 0
1 1 1
0 0 0
0 1 1
1 0 1
1 1 1
Example : int x = 10;
int y =
20; x
|y=?
x = 0000 1010
y = 0000 1011
x | y = 0000 1011 = 11
3. Bitwise Exclusive OR :
The XOR operator is denoted by a carrot (^) symbol.
It takes two values and returns true if they are different; otherwise returns false.
In binary, the true is represented by 1 and false is represented by 0.
Truth table of Bitwise XOR
Condition1 Condition2 Condition1 ^ Condition2
0 0 0
0 1 1
1 0 1
1 1 0
Example
ab+
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
+ab
CONTROL STATEMENTS
In java, the default execution flow of a program is a sequential order.
But the sequential order of execution flow may not be suitable for all situations.
Sometimes, we may want to jump from line to another line, we may want to skip a part of the
program, or sometimes we may want to execute a part of the program again and again.
To solve this problem, java provides control statements.
Types of Control Statements
class SampleSwitch
{
public static void main(String args[])
{
char color ='g';
switch(color )
{
case 'r':
[Link]("RED") ; break ;
case 'g':
[Link]("GREEN") ; break ;
case 'b':
[Link]("BLUE") ; break ;
case 'w':
[Link]("WHITE") ; break ;
default:
[Link]("No color") ;
}
}
}
2. Iteration Statements
The java programming language provides a set of iterative statements that are used to execute a
statement or a block of statements repeatedly as long as the given condition is true.
The iterative statements are also known as looping statements or repetitive statements. Java
provides the following iterative statements.
while statement
1.
do-while statement
2.
3. for statement
4. for-each statement
while statement in java
The while statement is used to execute a single statement or block of statements repeatedly as long as
the given condition is TRUE. The while statement is also known as Entry control looping statement.
Syntax
while(condition)
{
// body of loop
}
Example
If only one statement is being repeated, there is no need for the curly braces.
In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement. After the block of statements execution,
the modification statement gets executed, followed by condition again.
Example
public class ForTest
{
public static void main(String[] args)
{
for(int i = 0; i < 10; i++)
{
[Link]("i = " + i);
}
[Link]("Statement after for!");
}
}
3. Jump Statements
The java programming language supports jump statements that used to transfer execution control
from one line to another line.
The java programming language provides the following jump statements.
1. break statement
2. continue statement
break
When a break statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop.
Example
class BreakStatement
{
public static void main(String args[] )
{
int i;
i=1;
while(true)
{
if(i >10)
break;
[Link](i+" ");
i++;
}
}
}
Continue
This command skips the whole body of the loop and executes the loop with the next iteration. On
finding continue command, control leaves the rest of the statements in the loop and goes back to the
top of the loop to execute it with the next iteration (value).
Example
/* Print Number from 1 to 10 Except 5 */
class NumberExcept
{
public static void main(String args[] )
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
continue;
[Link](i +" ");
}
}
}
TYPE CONVERSION AND CASTING
Type Casting
When a data type is converted into another data type by a programmer using the casting operator
while writing a program code, the mechanism is known as type casting.
In typing casting, the destination data type may be smaller than the source data type when
converting the data type to another data type, that’s why it is also called narrowing conversion.
Syntax
destination_datatype = (target_datatype)variable;
Output
Before conversion: 166.66
After conversion into int type: 166
Type Conversion
If a data type is automatically converted into another data type at compile time is known as type
conversion.
The conversion is performed by the compiler if both data types are compatible with each other.
Remember that the destination data type should not be smaller than the source type.
It is also known as widening conversion of the data type.
Example
int a = 20;
Float b;
b = a; // Now the value of variable b is 20.000
Program
Output :
Documentation Section
The documentation section is an important section but optional for a Java program.
It includes basic information about a Java program. The information includes the author's name,
date of creation, version, program name, company name, and description of the program. It
improves the readability of the program. Whatever we write in the documentation section, the Java
compiler ignores the statements during the execution of the program. To write the statements in the
documentation section, we use comments.
Comments there are three types
1. Single-line Comment: It starts with a pair of forwarding slash (//).
2. Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
Example : /* It is an example of
multiline comment */
3. Documentation Comment: It starts with the delimiter (/**) and ends with */.
SAMPLE JAVA PROGRAM
/* This is First Java Program */
Class sample
{
public static void main(String args[])
{
[Link](“Hello Java Programming”);
}
}
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], [Link]().
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The core advantage
of the static method is that there is no need to create an object to invoke the static method. The main
method is executed by the JVM, so it doesn't require to create an object to invoke the main method. So it
saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program execution
String[] args is used for command line argument.
[Link]() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class.
How to Compile and Run the Java Program
To Compile : javac [Link] [ program name]
To Run : java Sample
Output : Hello Java Programming
EXECUTION PROCESS OF JAVA PROGRAM
WHAT IS JVM
Java Virtual Machine is the heart of entire java program execution process. It is responsible for taking
the .class file and converting each byte code instruction into the machine language instruction that can
be executed by the microprocessor.
CLASSES AND OBJECTS IN JAVA
CLASSES
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are
used to represent real-world concepts and entities.
classes usually consist of two things: instance variables and methods.
The class represents a group of objects having similar properties and behavior.
For example, the animal type Dog is a class while a particular dog named Tommy is an object of
the Dog class.
It is a user-defined blueprint or prototype from which objects are created. For example, Student is
a class while a particular student named Ravi is an object.
The java class is a template of an object.
Every class in java forms a new data type.
Once a class got created, we can generate as many objects as we want.
Class Characteristics
Identity - It is the name given to the class.
State - Represents data values that are associated with an object.
Behavior - Represents actions can be performed by an object.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects
are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
Data member
Method
Constructor
Nested Class
Interface
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as variables and
behaviors as methods.
Syntax
class className
{
data members declaration;
methods definition;
}
The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
The ClassName must follow all naming rules.
Example
Here is a class called Box that defines three instance variables: width, height, and depth.
class Box
{
double width;
double height;
double depth;
void volume()
{
………………….
}
}
OBJECT
//save by [Link]
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
[Link](); //Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
2. Private
The private access modifier is accessible only within the class.
The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in which
they are declared.
Any other class of the same package will not be able to access these members.
Top-level classes or interfaces can not be declared as private because private means “only visible
within the enclosing class”.
Example
In this example, we have created two classes A and Simple.
A class contains private data member and private method.
We are accessing these private members from outside the class, so there is a compile-time error.
class A
{
private int data=40;
private void msg()
{
[Link]("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
[Link]([Link]); //Compile Time Error
[Link](); //Compile Time Error
}
}
3. Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier is specified using the keyword protected.
Example
In this example, we have created the two packages pack and mypack.
The A class of pack package is public, so can be accessed from outside the package.
But msg method of this package is declared as protected, so it can be accessed from outside the
class only through inheritance.
//save by [Link]
package pack;
public class A
{
protected void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
[Link]();
}
}
4. Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
The public access modifier is specified using the keyword public.
Example
//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
[Link](id+" "+name);
}
class ThisDemo2
{
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry");
[Link]();
}
}
Output: 111 Harry
GARBAGE COLLECTION IN JAVA
Garbage collection in Java is the process by which Java programs perform automatic memory
management.
How Does Garbage Collection in Java works?
Java garbage collection is an automatic process.
Automatic garbage collection is the process of looking at heap memory, identifying which objects
are in use and which are not, and deleting the unused objects.
An unused or unreferenced object is no longer referenced by any part of your program.
So the memory used by an unreferenced object can be reclaimed.
The programmer does not need to mark objects to be deleted explicitly.
The garbage collection implementation lives in the JVM.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.
How Can an Object be Unreferenced?
There are many ways:
1. By nulling the reference
2. By assigning a reference to another
3. By anonymous object etc.
1. By nulling a reference:
1. Employee e=new Employee();
2. e=null;
3. By anonymous object:
1. new Employee();
OVERLOADING METHODS AND CONSTRUCTORS
OVERLOADING METHODS
Whenever same method name is exiting multiple times in the same class with different number of
parameter or different order of parameters or different types of parameters is known as method
overloading.
Method overloading in Java is also known as Compile-time Polymorphism, Static Polymorphism,
or Early binding.
Example
class Addition
{
void sum(int a, int b)
{
[Link](a+b);
}
void sum(int a, int b, int c)
{
[Link](a+b+c);
}
void sum(float a, float b)
{
[Link](a+b);
}
}
class Methodload
{
public static void main(String args[])
{
Addition obj=new Addition();
[Link](10, 20);
[Link](10, 20, 30);
[Link](10.05f, 15.20f);
}
}
OVERLOADING CONSTRUCTORS
Constructor overloading is a concept of having more than one constructor with different parameters
list, so that each constructor performs a different task.
Example
1. A class is created, but its name is decided by the compiler, which extends the Person class and
provides the implementation of the eat() method.
2. An object of the Anonymous class is created that is referred to by 'p,' a reference variable of Person
type.
3. LOCAL INNER CLASS
A class i.e. created inside a method is called local inner class in java.
If you want to invoke the methods of local inner class, you must instantiate this class inside the
method.
Example
public class localInner
{
private int data=30;
void display()
{
class Local
{
void msg()
{
[Link](data);
}
}
Local l=new Local();
[Link]();
}
public static void main(String args[])
{
localInner obj=new localInner();
[Link]();
}
}
4. STATIC NESTED CLASS
A static class i.e. created inside a class is called static nested class in java. It cannot access non-
static data members and methods. It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.
Example
class TestOuter
{
static int data=30;
static class Inner
{
void msg()
{
[Link]("data is "+data);
}
}
public static void main(String args[])
{
[Link] obj=new [Link]();
[Link]();
}
}
In this example, you need to create the instance of static nested class because it has instance method msg().
But you don't need to create the object of Outer class because nested class is static and static properties,
methods or classes can be accessed without object.
EXPLORING STRING CLASS
A string is a sequence of characters surrounded by double quotations. In a java programming
language, a string is the object of a built-in class String.
The string created using the String class can be extended. It allows us to add more characters after
its definition, and also it can be modified.
Example
String siteName = "javaprogramming";
siteName = "javaprogramminglanguage";
String handling methods
In java programming language, the String class contains various methods that can be used to handle
string data values.
The following table depicts all built-in methods of String class in java.
[Link] Method Description
1 charAt(int) Finds the character at given index
2 length() Finds the length of given string
3 compareTo(String) Compares two strings
4 compareToIgnoreCase(String) Compares two strings, ignoring case
5 concat(String) Concatenates the object string with argument string.
6 contains(String) Checks whether a string contains sub-string
7 contentEquals(String) Checks whether two strings are same
8 equals(String) Checks whether two strings are same
9 equalsIgnoreCase(String) Checks whether two strings are same, ignoring case
10 startsWith(String) Checks whether a string starts with the specified string
11 isEmpty() Checks whether a string is empty or not
12 replace(String, String) Replaces the first string with second string
Replaces the first string with second string at all
replaceAll(String, String)
13 occurrences.
Extracts a sub-string from specified start and end index
substring(int, int)
14 values
ECE
1. Sensor Monitoring System
2. Communication Device Configuration Software
3. Signal Processing Applications
EEE
1. Electricity Billing System
2. Power Consumption Monitoring System
3. Smart Energy Management
Mechanical Engineering
1. Machine Maintenance System
2. Production Monitoring System
3. Inventory Tracking System
Civil Engineering
1. Construction Cost Estimation System
2. Structural Analysis Application
3. Survey Data Processing System
1.3 GATE + Competitive Examination
Questions
GATE 2026
Question 1
What is the output?
class Test {
public static void main(String[] args) {
int x = 5;
[Link](x++ + ++x);
}
}
Answer: 12
Question 2
Which OOP concept allows one interface to be used for different data
types?
A) Encapsulation
B) Inheritance
C) Polymorphism
D) Abstraction
Answer: C) Polymorphism
GATE 2025
Question 3
What is the output?
class Test {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
[Link](s1 == s2);
}
}
Answer: true
Question 4
Which keyword is used to inherit a class in Java?
A) implement
B) extends
C) inherit
D) super
Answer: B) extends
GATE 2024
Question 5
What is the output?
class Test {
public static void main(String[] args) {
int a = 10;
int b = 20;
[Link](a > b ? a : b);
}
}
Answer: 20
Question 6
Which method is automatically called when an object is created?
A) finalize()
B) constructor
C) main()
D) static()
Answer: B) constructor
GATE 2023
Question 7
What is the output?
class Test {
public static void main(String[] args) {
for(int i=1;i<=3;i++)
[Link](i+" ");
}
}
Answer: 1 2 3
Question 8
Which of the following is not an access modifier?
A) private
B) protected
C) public
D) package
Answer: D) package
GATE 2022
Question 9
What is the output?
class Test {
public static void main(String[] args) {
String s = "JAVA";
[Link]([Link]());
}
}
Answer: 4
Question 10
Which class is immutable in Java?
A) StringBuilder
B) StringBuffer
C) String
D) ArrayList
Answer: C) String
GATE 2021
Question 11
Find the output.
class Test {
public static void main(String[] args) {
int i = 1;
while(i <= 3) {
[Link](i);
i++;
}
}
}
Answer: 123
Question 12
Which exception occurs when an array index exceeds its size?
Answer: ArrayIndexOutOfBoundsException
GATE 2020
Question 13
What is the output?
class Test {
public static void main(String[] args) {
int x = 0;
if(x == 0)
[Link]("Zero");
else
[Link]("Non-Zero");
}
}
Answer: Zero
Question 14
Which collection stores unique elements only?
A) ArrayList
B) Vector
C) HashSet
D) LinkedList
Answer: C) HashSet
GATE 2019
Question 15
What is the output?
class Test {
public static void main(String[] args) {
int a = 5;
[Link](a++);
}
}
Answer: 5
Question 16
Which package contains Scanner class?
A) [Link]
B) [Link]
C) [Link]
D) [Link]
Answer: C) [Link]
GATE 2018
Question 17
What is the output?
class Test {
public static void main(String[] args) {
int x = 10;
do {
[Link](x);
x++;
} while(x < 10);
}
}
Answer: 10
Question 18
Which keyword refers to the current object?
A) current
B) self
C) this
D) super
Answer: C) this
GATE 2017
Question 19
What is the output?
class Test {
public static void main(String[] args) {
int sum = 0;
for(int i=1;i<=5;i++)
sum += i;
[Link](sum);
}
}
Answer: 15
Question 20
Which OOP feature supports code reusability?
A) Inheritance
B) Encapsulation
C) Constructor
D) Method
Answer: A) Inheritance
GATE 2016
Question 21
What is the output?
class Test {
public static void main(String[] args) {
int x = 5;
int y = 10;
[Link](x + y);
}
}
Answer: 15
Question 22
Which of the following is not a primitive data type in Java?
A) int
B) float
C) String
D) char
Answer: C) String
Important Java Competitive
Questions
Question 23
Differentiate between String, StringBuffer, and StringBuilder.
Answer:
● String → Immutable
● StringBuffer → Mutable, Thread-safe
● StringBuilder → Mutable, Faster, Not Thread-safe
Question 24
Difference between Method Overloading and Method Overriding.
Answer:
Question 25
What are the four pillars of OOP?
Answer:
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
Question 26
What is Garbage Collection?
Answer:
Garbage Collection is the automatic memory management process in
Java that removes unused objects from memory.
Question 27
What is the difference between Abstract Class and Interface?
Answer:
Answer:
Defining multiple constructors in the same class with different
parameter lists.
Question 29
What is Exception Handling?
Answer:
A mechanism to handle runtime errors using:
● try
● catch
● finally
● throw
● throws
Question 30
What is the output?
class Test {
public static void main(String[] args) {
String s = "Java";
[Link]([Link]());
}
}
Answer: JAVA
1. What is the output of a Java program using constructor
overloading?
2. Differentiate between method overloading and method
overriding.
3. What is the purpose of the 'this' keyword?
4. Explain the scope of local and instance variables.
5. What are the advantages of OOP?
6. Explain type casting in Java with an example.
7. What is garbage collection?
8. Differentiate between String and StringBuffer.
9. Explain recursion with an example.
10. What is an inner class?
[Link](x++ + ++x);
A) 20
B) 21
C) 22
D) 23
Answer: C) 22
Answer: C) Abstraction
Answer: D) this
Answer: B) 4 bytes
2. Infosys
[Link]([Link]());
A) 3
B) 4
C) 5
D) Error
Answer: B) 4
Q2.
Which loop executes at least once?
A) for
B) while
C) do-while
D) nested loop
Answer: C) do-while
Q3.
What is the default value of an instance variable of type int?
A) null
B) 1
C) 0
D) Undefined
Answer: C) 0
Q4.
Which method is automatically invoked when an object is created?
A) finalize()
B) constructor
C) main()
D) static()
Answer: B) constructor
Q5.
Which operator is used for object creation?
A) create
B) alloc
C) new
D) malloc
Answer: C) new
3. Accenture
[Link](a++);
A) 5
B) 6
C) Error
D) 4
Answer: A) 5
Answer: D) String
Answer: B) break
Answer: B) toUpperCase()
4. Cognizant
int y = 10;
[Link](x > y ? x : y);
A) 5
B) 10
C) Error
D) 15
Answer: B) 10
Answer: C) switch
Answer: C) String
Answer: B) Inheritance
5. Capgemini
[Link](arr[1]);
A) 10
B) 20
C) 30
D) Error
Answer: B) 20
Answer: C) extends
A) 3.33
B) 3
C) 4
D) Error
Answer: B) 3
A) [Link]
B) [Link]
C) [Link]
D) [Link]
Answer: C) [Link]
B. GATE-Oriented Questions
4. Explain parameter passing mechanism in Java.
5. Differentiate between constructor overloading and method
overloading.
6. Write a Java program demonstrating recursion and analyze its
execution.
C. Placement-Oriented Questions
7. Write a Java program to find the largest of three numbers using
if-else statements.
8. Write a Java program to reverse a string.
9. Write a Java program to find factorial using recursion.
10. Write a Java program to demonstrate constructor overloading.
Important Note: