Unit 1 Java
Unit 1 Java
PREPARED BY
VERIFIED BY
1
CREDIT POINT
AFFILIATED INSTITUTIONS
R-2017
SEMESTER III
THEORY
1. MA8351 Discrete Mathematics 4 0 0 4
2. CS8351 Digital Principles and System Design 4 0 0 4
3. CS8391 Data Structures 3 0 0 3
4. CS8392 Object Oriented Programming 3 0 0 3
5. EC8394 Analog and Digital Communication 3 0 0 3
PRACTICALS
6. CS8381 Data Structures Laboratory 0 0 4 2
7. CS8383 Object Oriented Programming Laboratory 0 0 4 2
8. CS8382 Digital Systems Laboratory 0 0 4 2
9. HS8381 Interpersonal Skills/Listening & Speaking 0 0 2 1
TOTAL 17 0 14 24
2
SYLLABUS
CS8392 - OBJECT ORIENTED PROGRAMMING LTPC
30 03
UNIT IINTRODUCTION TO OOP AND JAVA FUNDAMENTALS 10
3
TOTAL: 45 PERIODS
TEXT BOOKS:
1. Herbert Schildt, “Java The complete reference”, 8th Edition, McGraw Hill Education,
2011.
2. Cay S. Horstmann, Gary cornell, “Core Java Volume –I Fundamentals”, 9th Edition,
Prentice Hall, 2013.
REFERENCES:
1. Paul Deitel, Harvey Deitel, “Java SE 8 for programmers”, 3rd Edition, Pearson, 2015.
2. Steven Holzner, “Java 2 Black book”, Dreamtech press, 2011.
3. Timothy Budd, “Understanding Object-oriented programming with Java”, Updated
Edition, Pearson Education, 2000.
4
UNIT I
5
LIST OF IMPORTANT QUESTIONS
UNIT 1
PART-A
1. What is javadoc.[N/D’19]
2. Define access specifier? [N/D’19][N/D’18]
3. Can a java source file be saved using a name other than the class name? justify.[A/M’19]
4. What are inline functions? Give examples. [A/M’19] or what are the advantages of an
inline function? [A/M’15]State the uses of Inline function[N/D’16]
5. Write the syntax for importing packages in a java source file and give an
example.[A/M’19]
6. State the conditions for method overriding in java.[A/M’19]
7. Define objects and classes in java? [N/D’18] [N/D’14][A/M’17]
8. Give an example for non-parameterized constructor [A/M’17]
9. Define the term Encapsulation. [A/M’17][M/J’14]
10. What is object oriented programming? [A/M’17][N/D’16][M/J’13]orWhat is OOPS
paradigm? Illustrate with example. [M/J’12] [M/J’16] [N/D’16]
11. “Java is platform independent language”. Comment [N/D’16] [A/M’17]
12. What is a package?[A/M’17]
13. What is Byte code? [A/M’17]
14. Define data abstraction.[M/J’16][A/M’15][M/J’13][M/J’12][N/D’13] or Define
Abstraction[N/D’16]
15. Define Polymorphism? [N/D’16]
16. What are the advantages of object oriented programming over structured
programming? [A/M’15][N/D’12] [N/D’11]
17. List the object oriented languages. [N/D’14]
18. Distinguish between class and object. [M/J’16][M/J’14]
19. Highlight the features of Java? [N/D’17]
20. Define the keyword static in java[N/D’15]
21. Distinguish between overloading and overriding? [ N/D’16]
22. What is JVM?[A/M’15]
6
PART B
1. Explain the various features of java in detail.[N/D’19] [N/D’16]or Explain the features
and characteristics of java [N/D’18] (13M)
2. What is JVM? Explain the internal architecture of JVM with neat sketch.[N/D’19](13M)
3. Discuss the 3 oop principles in detail? [A/M’19](7M)
4. What are literals? Explain the types of literals supported by java.[A/M’19](6M)
5. Explain the selection statements in java using suitable examples. [A/m’19] (7M)
6. Write a java code using do-while loop that counts down to 1 from 10 printing exactly
ten lines of “hello”.[A/M’19][6M]
7. Explain the characteristics of OOP? [N/D’18][A/M’17] (6M) Explain the characteristics of
OOPS. [N/D’16] [M/J’16] or Explain the major principles of object oriented programming
with illustrations and neat diagram. (16m) [A/M’15] (16m) [M/J’13] [M/J’12] [or] briefly
explain the key concepts of object oriented programming. (16m) [N/D’14] (12m) [N/D’11]
8. What is method? How method is defined? Give example? [N/D’18](6M)
9. State the purpose of finalize () method in java? With an example explain how finalize ()
method can be used in java program.[N/D’18](7M)
10. Write a java program to generate Fibonacci series.[N/D’17]
11. Explain how to declare arrays in java.Give examples.[N/D’17]
12. Explain the use of package in java with an illustrative example.[13m][N/D’17][N/D’15]
13. Explain the concept of polymorphism with an example?[8m][N/D’17]
14. List the applications of object oriented programming. [N/D’07] [N/D’16] [M/J’16]
15. Difference between Procedure Oriented Programming (POP) & Object Oriented
Programming (OOP) [M/J’16] [N/D’16][A/M’17]
16. Discuss the various types of operators in java and explain with suitable
example.[A/M’15][16M]
17. What is access modifier? Differentiate between private, protected and public access
modifiers with examples.[A/M’15][16M]
7
LIST OF IMPORTANT QUESTIONS
UNIT 1
PART-A
1. What is javadoc.[N/D’19]
Javadoc (originally cased JavaDoc) is a documentation generator created by Sun Microsystems
for the Java language (now owned by Oracle Corporation) for generating API documentation in
HTML format from Java source code. Writing comments and Javadoc is for better understanding
the code and thus better maintaining it.
2. Define access specifier? [N/D’19][N/D’18]
Definition : - Java Access Specifiers (also known as Visibility Specifiers ) regulate access to
classes, fields and methods in Java. These Specifiers determine whether a field or method in a
class, can be used or invoked by another method in another class or sub-class. Access
Specifiers can be used to restrict access.
3. Can a java source file be saved using a name other than the class name? justify.[A/M’19]
Yes, you can save your java source code file with any other name, not same as your main class
(public)name but when you compile it than byte code file name will be same as your main class
name.If there is any public class in file then in that case you have to give that name as file name.
4. What are inline functions? Give examples. [A/M’19] or what are the advantages of an inline
function? [A/M’15]State the uses of Inline function[N/D’16]
If a function is inline, the compiler places a copy of the code of that function at each point where
the function is called at compile time. No, Java does not provide inline functions it is typically
done by the JVM at execution time.
Advantages of inline function:
Inline function instruct compiler to insert complete body of the function wherever that function got
used in code.
Advantages :-
1) It does not require function calling overhead.
2) It also save overhead of variables push/pop on the stack, while function calling.
3) It also save overhead of return call from a function.
Use of inline function in java: No, there is no inline function in java. Yes, you can use a public
static method anywhere in the code when placed in a public class. The java compiler may do
inline expansion on a static or final method, but that is not guaranteed.
8
5. Write the syntax for importing packages in a java source file and give an example.[A/M’19]
To import java package into a class, we need to use java import keyword which is used to access
package and its classes into the java program. Use import to access built-in and user-defined
packages into your java source file so that your class can refer to a class that is in another
package by directly using its name.
Simple.java
package mypack;
{ System.out.println("Welcome to package");
}}
6. State the conditions for method overriding in java.[A/M’19]
1. In java, a method can only be written in subclass, not in same class.
2. The argument list should be exactly the same as that of the overridden method.
3. A method declared final cannot be overridden.
4. The access level cannot be more restrictive than the overridden method’s access level.
For eg; if the super class method is declared public then the over-ridding method in the sub
class cannot be either private or protected.
7. Define objects and classes in java? [N/D’18] [N/D’14][A/M’17]
Everything in Java is associated with classes and objects, along with its attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as weight and color, and
methods, such as drive and brake. A Class is like an object constructor, or a "blueprint" for
creating objects.To create a class, use the keyword class:
Public class Myclass{ int x=5;
Object:
In Java, an object is created from a class. Now, to create an object of MyClass, specify the class
name, followed by the object name, and use the keyword new,
Example:Create an object called "myObj" and print the value of
x: Public class MyClass{
int x =5;
public static void main(String[ ] args)
9
{
MyClass myobj = new MyClass();
System.out.println(myObj.x);}}
8. Give an example for non-parameterized constructor[A/M’17]
No-Arg constructor - a constructor that has no parameter is known as default constructor. If we don’t
define a constructor in a class, then compiler creates default constructor (with no arguments) for the
class. Default constructor provides the default values to the object like 0 ,null etc.
Example: Class Bike1{
Bike1() //Default constructor { System.out.println(“Bike is created”);}
Public static void main(String
args[])} Bike1 b=new Bike1();}}
9. Define the term Encapsulation. [A/M’17][M/J’14]
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines. A java class is the example of encapsulation.
10. What is object oriented programming? [A/M’17][N/D’16][M/J’13] or What is OOPS
paradigm? Illustrate with example. [M/J’12] [M/J’16] [N/D’16]
Oop stands for object-Oriented Programming. Procedural programming is about writing
procedures or methods that perform operations on the data, while object-orientted programming
is about creating objects that contain both data and methods.
11. “Java is platform independent language”. Comment [N/D’16] [A/M’17]
Java is platform-independent because it does not depend on any type of platform. Hence, java is
platform-independent language.
In java ,programs are compiled into byte code and that byte code is platform independent.
This byte code is sent to Java virtual Machine(JVM) which resides in the RAM of any operating
system.JVM recognizes the platform it is on and coverts the bytecode into native machine code.
10
12. What is a package?[A/M’17]
A package in java is used to group related classes.It as a folder in a file directory.It use
packages to avoid name conflicts ,and to write a better maintainable code.Packages are
divided into two categories: Built-in Packages(Packages from the Java API)User-defined
Packages(create your own packages)
13. What is Byte code? [A/M’17]
Bytecode is program code that has been compiled from source code into low-level code
designed for a software interpreter.It may be executed by a virtual machine(such as a JVM)or
further compiled into machine code,which is recognized by the processor.
14. Define data abstraction.[M/J’16] [A/M’15] [M/J’13] [M/J’12] [N/D’13] or Define Abstraction
[N/D’16]
Data abstraction is the process of hiding certain details and showing only essential
information to the user.
Abstraction can be achieved with either abstract classes or interfaces.
15. Define Polymorphism? [N/D’16]
Polymorphism means “many forms” and it occurs when we have many classes that are
related to each other by inheritance. Inheritance let us inherit attributes and methods from
another class. Polymorphism uses those methods to perform different tasks.
16. What are the advantages of object oriented programming over structured programming?
[A/M’15] [N/D’12] [N/D’11]
• Modularity for easier troubleshooting
• Reuse of code through inheritance
• Flexibility through polymorphism
• Effective problem solving
17. List the object oriented languages. [N/D’14] C+
+,Java,C#,Python,R,PHP,Ruby,Perl,javaScript,Dart,Swift,Scala,Kotlin,CommonLisp,
MATLAB and Smalltalk.
11
18. Distinguish between class and object. [M/J’16][M/J’14]
Class Object
A class is a blueprint from which An object is the instance of the class, which helps
you can create the instance, i.e., programmers to use variables and methods from
objects. inside the class.
A class doesn't take any memory An object takes memory when a programmer
spaces when a programmer
creates one.
creates one.
The class has to be declared only Objects can be declared several times depending
once. on the requirement.
12
same variable or method of a given class. Basically , static is used for a constant variable or
a method that is same for every instance of a class.
21. Distinguish between overloading and overriding? [ N/D’16]
Method overloading Method over-riding
Method overloading is used to increase Method overriding is used to provide the
the readability of the program. specific implementation of the method that
already provided by its super class.
1. Explain the various features of java in detail.[N/D’19][N/D’16]or Explain the features and
characteristics of java [N/D’18] (13M)
The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features
which play an important role in the popularity of this language. The features of Java are also
known as java buzzwords. A list of most important features of Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
13
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language. A
platform is the hardware or software environment in which a program runs. There are two types of
platforms software-based and hardware-based. Java provides a software-based platform. The Java
platform differs from most other platforms in the sense that it is a software-based platform that runs
on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
14
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
etc. Java code is compiled by the compiler and converted into bytecode.This bytecode is a
platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which is used
to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network
sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
15
Robust
Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid
of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points
make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode
is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is
an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and
EJB are used for creating distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-threading
is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are
important for multi-media, Web applications, etc.
16
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages, i.e., C and C++.Java supports
dynamic compilation and automatic memory management (garbage collection).
2. What is JVM? Explain the internal architecture of JVM with neat sketch.[N/D’19](13M)
Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the Java
Code or applications. It converts Java bytecode into machines language. JVM is a part of Java
Run Environment (JRE). In other programming languages, the compiler produces machine code
for a particular system. However, Java compiler produces code for a Virtual Machine known as
Java Virtual Machine.
JVM works
First, Java code is complied into bytecode. This bytecode gets interpreted on different machines
Between host system and Java source, Bytecode is an intermediary language.
JVM is responsible for allocating memory space.
JVM Architecture
Let's understand the Architecture of JVM. It contains classloader, memory area, execution engine
etc.
17
1) ClassLoader
The class loader is a subsystem used for loading class files. It performs three major functions viz.
Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant runtime pool, and the code
for methods.
3) Heap
All the Objects, their related instance variables, and arrays are stored in the heap. This memory is
common and shared across multiple threads.
4) JVM language Stacks
Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM
stack, created simultaneously as the thread is created. A new frame is created whenever a method
is invoked, and it is deleted when method invocation process is complete.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently executing.
In Java, each thread has its separate PC register.
6) Native Method Stacks
Native method stacks hold the instruction of native code depends on the native library. It is written
in another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems. The test execution
engine never carries any information about the tested product.
8) Native Method interface
The Native Method Interface is a programming framework. It allows Java code which is running in
a JVM to call by libraries and native applications.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution
Engine.
3. Discuss the 3 oop principles in detail? [A/M’19](7M)
Encapsulation, inheritance, and polymorphism are usually given as the three fundamental
principles of object-oriented languages (OOLs) and object-oriented methodology.
18
1. Encapsulation
Encapsulation means binding all methods and classes in a single class. Encapsulation is the
technique of making the fields in a class private and providing access to the fields via public
methods. If a field is declared private then it cannot be accessed by anyone outside the class,
thereby hiding the fields within the class.
The main benefit of encapsulation is the ability to modify our implemented code without
breaking the code of others who use our code.
Encapsulation provides maintainability, flexibility and extensibility of our code.
2. Inheritance
The main feature of Inheritance is code re-usability. So when making a new class we can use
a previously written class and further extend it. In Java, classes may inherit or acquire the
properties and methods of other classes.
A class derived from another class is called a subclass, whereas the class from which a
subclass is derived is called a super class. A subclass can have only one super class, whereas a
super class may have one or more sub-classes.
Example:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){ Programmer
p=new Programmer(); System.out.println("Programmer
salary is:"+p.salary); System.out.println("Bonus of
Programmer is:"+p.bonus);
}
}
Output: Programmer salary is:40000.0
Bonus of programmer is:10000
19
3. Polymorphism
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.If you overload a static method in Java, it is the example of compile time polymorphism.
Here, we will focus on runtime polymorphism in java.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.
For example:
class A{}
class B extends A{}
A a=new B();//upcasting
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with
60km");} public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
}
Output:
running safely with 60km.
20
4. What are literals? Explain the types of literals supported by java.[A/M’19](6M)
Java Literals: A literal in java refers to a fixed value that appears directly in a program. Java
define five primary types of literals. By literal we mean any number, text, or other information
that represents a value. This means what you type is what you get. They are commonly known
as constants. We will use literals in addition to variables in Java statement.
In Java programming language there are five type of literals that literals can be classified as
integer literals, floating-point literals, character literals, string literals and boolean literals. Java
literals can be of primitive data types. The way each literal is represented depends upon it type.
Integral Literals in Java
We can specify the integer literals in 4 different ways –
• Decimal (Base 10)
Digits from 0-9 are allowed in this form.
1. Int x = 101;
• Octal (Base 8)
Digits from 0 – 7 are allowed. It should always have a prefix 0.
1. int x = 0146;
1. int x = 0X123Face;
• Binary
A literal in this type should have a prefix 0b and 0B, from 1.7 one can also specify in binary
literals, i.e. 0 and 1.
1. int x = 0b1111;
Example-
package com.dataflair.literals;
public class IntegralLiteral {
public static void main(String[] args)
21
{int decimalValue = 123; // decimal-form literal
int octalValue = 01200; // octal-form literal
int hexaDecimalValue = 0xAce; // Hexa-decimal form literal
int binaryValue = 0b00101; // Binary literal
System.out.println("Decimal form literal is "+decimalValue);
System.out.println("Octal form literal is "+b);
System.out.println("Hexa-decimal form literal is "+hexaDecimalValue);
System.out.println("Binary literal is "+binaryValue);
}}
Output
Decimal form literal is 123
Octal form literal is 640
Hexa-decimal form literal 2766
Binary literal is 5
Floating-Point Literals in Java
Here, datatypes can only be specified in decimal forms and not in octal or hexadecimal form.
• Decimal (Base 10)
package com.dataflair.literals;
public class FloatingPointLiteral
{public static void main(String args[])
{double decimalValue = 101.230; // decimal-form literal
double decimalValue1 = 0123.222; // It also acts as decimal literal
double hexaDecimalValue = 1.234e2; // Hexa-decimal form
System.out.println("Decimal form literal is "+decimalValue);
System.out.println("Second Decimal form literal is "+decimalValue1);
System.out.println("Hexa decimal form literal is "+hexaDecimalValue);}}
Output –
Decimal form literal is 101.23
Second Decimal form literal is 123.222
Hexa decimal form literal is123.4
22
3. Char Literals in Java
These are the four types of char-
• Single Quote
Java Literal can be specified to a char data type as a single character within a single quote.
1. char ch = 'a';
• Char as Integral
A char literal in Java can specify as integral literal which also represents the Unicode value of a
character.
Furthermore, an integer can specify in decimal, octal and even hexadecimal type, but the range is
0-65535.
1. char ch = 062;
• Unicode Representation
Char literals can specify in Unicode representation ‘\uxxxx’. Here XXXX represents 4 hexadecimal
numbers.
• Escape Sequence
Escape sequences can also specify as char literal.
1. char ch = '\n';
Example-
package com.dataflair.literals;
public class CharacterLiteral {
public static void main(String[] args)
{char character = 'd';
//char number = 0789; error: Integer number too large
char unicodeCharacter = '\u0064';
System.out.println(character);
System.out.println(unicodeCharacter);
System.out.println("\" is a symbol"); }}
Output –
23
d
d
“ is a symbol
4. String Literals
Java String literals are any sequence of characters with a double quote.
1. String s = "Hello";
They may not contain unescaped newline or linefeed characters.However, the Java compiler will
evaluate compile-time expressions.
Example
package com.dataflair.literals;
public class StringLiteral {
public static void main(String[] args)
{ String myString = "Hello! Welcome to DataFlair";
// If we assign without "" then it treats as a
variable // and causes compiler error
// String myString1 = Hello;
System.out.println(myString );
}}
Output: Hello! Welcome to DataFlair
Boolean Literals
They allow only two values i.e. true and false.
1. boolean b = true;
Example –
package com.dataflair.literals;
public class BooleanLiteral { public
static void main(String[] args)
{boolean boolVar1 = true; boolean
boolVar2 = false;
// boolean boolVar3 = 0; error: incompatible types: int cannot be converted to boolean
// boolean boolVar1 = 1; error: incompatible types: int cannot be converted to Boolean
24
System.out.println(boolVar1);
System.out.println(boolVar2);
}}
Output
true
false
5. Explain the selection statements in java using suitable examples. [A/m’19] (7M)
Java has three types of selection statements. The if statement either performs (selects) an
action, if a condition is true, or skips it, if the condition is false.
The if...else statement performs an action if a condition is true and performs a different action if
the condition is false. The switch statement performs one of many different actions, depending on
the value of an expression.
The if statement is a single-selection statement because it selects or ignores a single action
(or, as we’ll soon see, a single group of actions). The if...else statement is called a double-
selection statement because it selects between two different actions (or groups of actions). The
switch statement is called a multiple-selection.
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:
//Java Program to demonstrate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
} } }
Output:
Age is greater than 18
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
25
Syntax:
if(condition){
//code if condition is true
} else {
//code if condition is false
}
Example:
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args)
{
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
} else{
System.out.println("odd number");
} } }
Output:
odd number
26
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
} } }
Output:
20
6. Write a java code using do-while loop that counts down to 1 from 10 printing exactly ten
lines of “hello”.[A/M’19][6M]
In java:
public class Hello {
public static void main(String [] args) {
for (int i =0; i <10; i++) {
System.out.println ("Hello ");
}}}
7. Explain the characteristics of OOP? [N/D’18][A/M’17] (6M) Explain the characteristics of
OOPS. [N/D’16] [M/J’16] or Explain the major principles of object oriented programming
with illustrations and neat diagram. (16m) [A/M’15] (16m) [M/J’13] [M/J’12] [or] briefly
explain the key concepts of object oriented programming. (16m) [N/D’14] (12m) [N/D’11]
OOP concepts in Java are the main ideas behind Java’s Object Oriented Programming. They are
an abstraction, encapsulation, inheritance, and polymorphism. Grasping them is key to
understanding how Java works. Basically, Java OOP concepts let us create working methods and
variables, then re-use all or part of them without compromising security. List of OOP Concepts in
Java
There are four main OOP concepts in Java. These are:
• Abstraction. Abstraction means using simple things to represent complexity. We all know how to
turn the TV on, but we don’t need to know how it works in order to enjoy it. In Java, abstraction
means simple things like objects, classes, and variables represent more complex underlying
code and data. This is important because it lets avoid repeating the same work multiple times.
27
• Encapsulation. This is the practice of keeping fields within a class private, then providing access
to them via public methods. It’s a protective barrier that keeps the data and code safe within the
class itself. This way, we can re-use objects like code components or variables without allowing
open access to the data system-wide.
• Inheritance. This is a special feature of Object Oriented Programming in Java. It lets programmers
create new classes that share some of the attributes of existing classes. This lets us build on
previous work without reinventing the wheel.
• Polymorphism. This Java OOP concept lets programmers use the same word to mean different things
in different contexts. One form of polymorphism in Java is method overloading. That’s when different
meanings are implied by the code itself. The other form is method overriding. That’s when the
different meanings are implied by the values of the supplied variables. See more on this below.
How Abstraction Works
Abstraction as an OOP concept in Java works by letting programmers create useful, reusable
tools. For example, a programmer can create several different types of objects. These can be
variables, functions, or data structures. Programmers can also create different classes of objects.
These are ways to define the objects.
For instance, a class of variable might be an address. The class might specify that each address
object shall have a name, street, city, and zip code. The objects, in this case, might be employee
addresses, customer addresses, or supplier addresses.
How Encapsulation Works
Encapsulation lets us re-use functionality without jeopardizing security. It’s a powerful OOP
concept in Java because it helps us save a lot of time. For example, we may create a piece of code
that calls specific data from a database. It may be useful to reuse that code with other databases or
processes. Encapsulation lets us do that while keeping our original data private. It also lets us alter
our original code without breaking it for others who have adopted it in the meantime.
How Inheritance Works
Inheritance is another labor-saving Java OOP concept. It works by letting a new class adopt the
properties of another. We call the inheriting class a subclass or a child class. The original class is
often called the parent. We use the keyword extends to define a new class that inherits properties
from an old class.
28
How Polymorphism Works
Polymorphism in Java works by using a reference to a parent class to affect an object in the child
class. We might create a class called “horse” by extending the “animal” class. That class might also
implement the “professional racing” class. The “horse” class is “polymorphic,” since it inherits
attributes of both the “animal” and “professional racing” class.
Two more examples of polymorphism in Java are method overriding and method overloading.
In method overriding, the child class can use the OOP polymorphism concept to override a
method of its parent class. That allows a programmer to use one method in different ways
depending on whether it’s invoked by an object of the parent class or an object of the child class.
In method overloading, a single method may perform different functions depending on the
context in which it’s called. That is, a single method name might work in different ways depending
on what arguments are passed to it
8. What is method? How method is defined? Give example? [N/D’18](6M)
A method in Java is a set of instructions that can be called for execution using the method
name. A Java method can take in data or parameters and return a value - both parameters and
return values are optional. Methods can be public, private or protected.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we
have shown in the following figure.
29
Method Signature: Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our application. o
Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It
is enclosed within the pair of curly braces.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
o Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
o Let's see an example of the predefined method.
30
Demo.java
public class Demo
{ public static void main(String[] args)
{ // using the max() method of Math class System.out.print("The
maximum number is: " + Math.max(9,7));
}}
Output:
The maximum number is: 9
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
How to Create a User-defined Method
Let's create a user defined method that checks the number is even or odd. First, we will define
the method.
//user defined method
public static void findEvenOdd(int num)
{ //method body if(num%2==0)
System.out.println(num+" is
even"); else
System.out.println(num+" is odd");
}
We have defined the above method named findevenodd(). It has a parameter num of type int.
The method does not return any value that's why we have used void. The method body contains
the steps to check the number is even or odd. If the number is even, it prints the number is even,
else prints the number is odd.
How to Call or Invoke a User-defined Method
Once we have defined a method, it should be called. The calling of a method in a program is
simple. When we call or invoke a user-defined method, the program control transfer to the
called method.
EvenOdd.java
import java.util.Scanner;
public class EvenOdd
31
{ public static void main (String args[])
{ //creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number:
"); //reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
} //user defined method
public static void findEvenOdd(int
num) { //method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}}
Output :
Enter the number: 12
12 is even
Static Method
A method that has static keyword is known as static method
Example of static method
Display.java
public class Display
{ public static void main(String[] args)
{ show();
} static void show()
{ System.out.println("It is an example of static method.");
}}
Output:It is an example of a static method.
Instance Method
The method of the class is known as an instance method. It is a non-static method defined in
the class.
InstanceMethodExample.java
public class InstanceMethodExample
{
public static void main(String [] args)
{ //Creating an object of the class
32
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
} int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{ s = a+b;
//returning the
sum return s;
}}
Output:
The sum is: 25
There are two types of instance method:
o Accessor Method
o Mutator Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor
method. We can easily identify it because the method is prefixed with the word get. It is also known as
getters. It returns the value of the private field. It is used to get the value of the private field.
Mutator Method: The method(s) read the instance variable(s) and also modify the values. We
can easily identify it because the method is prefixed with the word set. It is also known as setters
or modifiers. It does not return anything. It accepts a parameter of the same data type that
depends on the field. It is used to set the value of the private field
33
{ System.out.println("Roll no.: "+roll);
System.out.println("Student name: "+name);
}}
Abstract Method
The method that does not has method body is known as abstract method. In other words, without
an implementation is known as abstract method. It always declares in the abstract class. It
means the class itself must be abstract if it has abstract method. To create an abstract method,
we use the keyword abstract.
9. State the purpose of finalize () method in java? With an example explain how finalize ()
method can be used in java program.[N/D’18](7M)
Object. finalize() is called by the garbage collector on an object when garbage collection
determines that there are no more references to the object. A subclass overrides the finalize
method to dispose of system resources or to perform other cleanup.
Example
34
try {
// create a new ObjectDemo object
ObjectDemo cal = new ObjectDemo();// print current time
System.out.println("" + cal.getTime()); // finalize cal
System.out.println("Finalizing...");
cal.finalize();
System.out.println("Finalized."); } catch (Throwable ex) {
ex.printStackTrace();
} }}
Output: Sun Aug 16 16:28:48 UTC 2020 Finalizing... Finalized.
35
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}} Output:33 3 4 5
12. Explain the use of package in java with an illustrative example.[13m][N/D’17][N/D’15]
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
36
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
} }
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
o Compile: javac -d . Simple.java
o Run: java mypack.Simple
Output: Welcome to package
37
// Java program for Method overloading
class MultiplyFun { // Method with 2 parameter
static int Multiply(int a, int b)
{ return a * b;
} // Method with the same name but 2 double parameter
static double Multiply(double a, double b)
{ return a * b;
}}
class Main {
public static void main(String[] args)
{ System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(5.5, 6.3)); } } Output: 8 34.65
38
a = new subclass1(); a.Print();
a = new subclass2(); a.Print(); }} Output:subclass1 subclass2
14. List the applications of object oriented programming. [N/D’07] [N/D’16] [M/J’16]
• Desktop Applications such as acrobat reader, media player, antivirus, etc.
• Web Applications such as irctc.co.in, javatpoint.com, etc.
• Enterprise Applications such as banking applications.
• Mobile
• Embedded System
• Smart Card , Robotics and Games, etc.
15. Difference between Procedure Oriented Programming (POP) & Object Oriented
Programming (OOP) [M/J’16] [N/D’16][A/M’17]
PROCEDURAL ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING
any proper way for hiding data so it is less Object oriented programming provides
secure. data hiding so it is more secure.
6.In procedural programming, overloading is Overloading is possible in object oriented
not possible. programming.
7.In procedural programming, function is In object oriented programming, data is
more important than data. more important than function.
8.Procedural programming is based Object oriented programming is based
on unreal world. Examples: C, FORTRAN, on real world. Examples: C++, Java,
Pascal, Basic etc. Python, C# etc.
39
16. Discuss the various types of operators in java and explain with suitable
example.[A/M’15][16M]
Operators in Java: Operator in Java is a symbol which is used to perform operations. For example:
+, -, *, / etc.There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator, Ternary Operator and Assignment Operator.
Additive +-
Equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary Ternary ?:
40
Java Unary Operator Example: ++ and --
class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10 }} Output:10 12 12 10
Java Arithmetic Operator Example
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0 }} Output: 15 5 50 2 0
Java Shift Operator Example: >> vs >>>
class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2); }} Output: 5 5 -5 1073741819
Java Ternary Operator
Java Ternary operator is used as one liner replacement for if-then-else statement and
used a lot in Java programming. it is the only conditional operator which takes three
operands.
Java Ternary Operator Example
class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}} Output: 2
Java Assignment Operator
Java assignment operator is one of the most common operator. It is used to assign
the value on its right to the operand on its left.
41
Java Assignment Operator Example
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}} Output: 14 16
Java AND Operator Example: Logical && vs Bitwise &
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}} Output: false 10 false 11
17. What is access modifier? Differentiate between private, protected and public access
modifiers with examples.[A/M’15][16M]
An access modifier is a keyword that we can apply to a member of a class to control its access
from the outside. Access modifiers are used to control the access of class members
(properties/fields and methods/functions) from outside of the class.
There are four types of access modifiers available in java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
42
Default: When no access modifier is specified for a class , method or data member – It
is said to be having the default access modifier by default.
• The data members, class or methods which are not declared using any access
modifiers i.e. having default access modifier are accessible only within the
same package.
//Java program to illustrate default modifier
package p1;
//Class Modifier is having Default access
modifier class Modifier
{ void display() { System.out.println("Hello World!"); } }
Private: 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 same package will not be able to access these members.
• Top level Classes or interface can not be declared as private because
1. private means “only visible within the enclosing class”.
2. protected means “only visible within the enclosing class and any subclasses”
Hence these modifiers in terms of application to classes, they apply only to
nested classes and not on top level classes
44