STS Cat-1 (Java)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2662

Module 1

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
What is Programming?
• Programming is the process of writing an algorithm into a sequence of computer instructions.
Or you can simply say it is the process of writing programs.
• The process of transforming the solution of a specific problem into computer language.
• Programming requires skill, logical thinking and lots of experience.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Who is a Programmer?
• Programmers are the person who writes programs in a specific computer programming
language.
• They are highly skilled, hard working, problem solvers.
• The world’s first programmer was Ada Lovelace. She was widely known for her work on
Charles Babbage’s Analytical Engine

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Classification of Programming Languages
• Different languages have different purposes. Some types are:

• Machine languages, that are interpreted directly in hardware


• Assembly languages, that are thin wrappers over a corresponding machine language
• High-level languages, that are anything machine-independent
• System languages, that are designed for writing low-level tasks, like memory and process
management
• Scripting languages, that are generally extremely high-level and powerful
• Domain-specific languages, that are used in highly special-purpose areas only
• Visual languages, that are non-text based
• Esoteric languages, that are not really intended to be used, but are very interesting, funny, or
educational in some way

• These types are not mutually exclusive: Perl is both high-level and scripting; C is considered both high-level
and system.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Assembler Vs Compiler Vs Interpreter
• Compiler :
Compilers are used to convert high level languages (like C, C++ ) into machine code .
– Example : gcc , Microsoft Visual Studio
• Assembers :
Assembler are used to convert assembly language code into machine code.
– Examples : List of assembler
• Interpreter :
An interpreter is a computer program which executes a statement directly (at runtime).
– Examples: python , LISP

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Objectives

In this session, you will learn to:


Get familiar with Java
Identify the building blocks of a Java program
Access class members

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introducing Java

Scenario:

The game must be


compatible across
various operating
systems.
Needs to create a
jumbled word game
named Classic
Jumble Word.
The code of the
game should be
efficiently written to
ensure minimum
complexity.

Sam

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introducing Java (Contd.)

Scenario (Contd.):

To cater to the preceding requirements,


Sam uses the Java programming
language.
Due to its powerful features and
underlying architecture, Java is used
widely as a programming language to
create efficient console or GUI based
applications.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Identifying the Features of Java
Some of the features of Java are:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Architecture
The Java architecture defines the components that are essential to
carry out the creation and execution of code written in the Java
programming language.
The various components of the Java architecture are:

Source file

Application
Programming Class file
Interface

JVM

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Architecture (Contd.)
The various components in the Java architecture are shown in the
following figure.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Architecture (Contd.)

The source code of a Java application is saved in a source file with


the extension, .java.
JVM is responsible for executing the bytecode and generating the
machine specific code for the machine on which the Java program
needs to be executed.
The Java API is a collection of software components, such as
classes, interfaces, and methods.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Source File- Extension - .java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Class File – Extension - .class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Application Programming Interface - API

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
How to set path in Java

• If you are saving the Java source file inside the JDK/bin directory, the path is not required to
be set because all the tools will be available in the current directory.

• There are two ways to set the path in Java:


o Temporary
o Permanent

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
How to set the Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow the following steps:
• Open the command prompt
• Copy the path of the JDK/bin directory
• Write in command prompt: set path= C:\Program Files\Java\jdk-14.0.1\bin

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
How to set Permanent Path of JDK in Windows

• For setting the permanent path of JDK, you need to follow these steps:
• Go to
MyComputer properties ->
advanced tab ->
environment variables ->
new tab of user variable ->
write path in variable name -> and paste the copied path
write path of bin folder in variable value -> ok -> ok -> ok

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Just a minute
Which one of the following features of Java allows a program to
simultaneously execute multiple tasks?
Multithreading
Portability
Distributed
Garbage collection

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Just a minute (Contd.)
Solution:
Multithreading

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Module 1

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
What is Programming?
• Programming is the process of writing an algorithm into a sequence of computer instructions.
Or you can simply say it is the process of writing programs.
• The process of transforming the solution of a specific problem into computer language.
• Programming requires skill, logical thinking and lots of experience.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Who is a Programmer?
• Programmers are the person who writes programs in a specific computer programming
language.
• They are highly skilled, hard working, problem solvers.
• The world’s first programmer was Ada Lovelace. She was widely known for her work on
Charles Babbage’s Analytical Engine

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Classification of Programming Languages
• Different languages have different purposes. Some types are:

• Machine languages, that are interpreted directly in hardware


• Assembly languages, that are thin wrappers over a corresponding machine language
• High-level languages, that are anything machine-independent
• System languages, that are designed for writing low-level tasks, like memory and process
management
• Scripting languages, that are generally extremely high-level and powerful
• Domain-specific languages, that are used in highly special-purpose areas only
• Visual languages, that are non-text based
• Esoteric languages, that are not really intended to be used, but are very interesting, funny, or
educational in some way

• These types are not mutually exclusive: Perl is both high-level and scripting; C is considered both high-level
and system.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Assembler Vs Compiler Vs Interpreter
• Compiler :
Compilers are used to convert high level languages (like C, C++ ) into machine code .
– Example : gcc , Microsoft Visual Studio
• Assembers :
Assembler are used to convert assembly language code into machine code.
– Examples : List of assembler
• Interpreter :
An interpreter is a computer program which executes a statement directly (at runtime).
– Examples: python , LISP

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Programming paradigms
• There are many different approaches to computer programming. These are called programming paradigms.
• Different approaches develop solutions to problems using programs using different paradigms.

• Even though most of the programming languages come under


one paradigm type, certain languages show elements related to
different paradigms.
• There are a number of programming languages. There are
differences among different programming language types.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Imperative Programming
• Imperative programming is the style of programming in which there is a sequence of statements that
change the state of the program.

Example : • The state of the total variable changed from 0 in the beginning of the program,
var total = 0; to 6 before the print function.
var a = 1;
var b = 5; • Imperative programming says how to do something. An example - the process
total = a + b of baking a cake.
print total;
• The program says how to do something in the correct sequence it should be
done, therefore order of execution (the order in which each statement is
executed) is important

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Declarative Programming
• Declarative programming is a programming paradigm … that expresses the logic of a
computation without describing its control flow.
– Examples would be HTML, XML, CSS, SQL, Prolog, Haskell, F#and Lisp.
• Declarative code focuses on building logic of software without actually describing its flow.
You are saying what without adding how.
– For example with HTML you use <img src="./image.jpg" />
– To tell browser to display an image and you don’t care how it does that.
• Imperative: C, C++, Java
• Declarative: SQL, HTML
• (Can Be) Mix: JavaScript, C#, Python

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example of Imperative and equivalent in Declarative

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OBJECT ORIENTED PROGRAMMING - OOP
• Object Oriented Programming is a popular methodology of programming any application.
• Java, is an Object Oriented Programming language.
• It allows users create the objects that they want and then create methods to handle those objects.
• Manipulating these objects to get results is the goal of Object Oriented Programming
• Object Oriented programming is a programming paradigm that is associated with the concept of Class and
Objects
• The four principles of object-oriented programming are,
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OBJECT ORIENTED PROGRAMMING - OOP
• OOP is designed in such a way that one should focus on an object while programming and
not the procedure.
• An object can be anything that we see around us.
• Object oriented programming brings programming close to real life, as we are always dealing
with an object, performing operations on it, using it's methods and variables etc.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
WHY OOPS
1. OOP provides a clear modular structure for programs
2. OOP makes it easy to maintain and modify existing code
3. OOP provides a good framework for code libraries where supplied software components can be
easily adapted and modified by the programmer.
4. Code Reusability
5. It is suitable for real world problems and real world works
6. OOPs lets the coder to change the implementation of an object without affecting any other code.
(Encapsulation)
7. OOPs lets the coder to think about what should be exposed to the outside world and what should
be hidden. (Abstraction)
8. OOPs allows the coder to have many different functions, all with the same name, all doing the
same job, but on different data. (Polymorphism)
9. OOPs lets the coder to write a set of functions, then expand them in different direction without
changing or copying them in any way. (Inheritance)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - CLASS
• A class is a template or blueprint that is used to create objects.
• The class is a group of similar entities.
• A class consists of Data members and methods.
• The member functions determine the behavior of the class, i.e. provide a definition for supporting various
operations on data held in the form of an object.
• It is only an logical component and not the physical entity.
– For example, if you had a class called “Expensive Cars” it could have objects like Mercedes,
BMW, Toyota, etc. Its properties(data) can be price or speed of these cars. While the methods
may be performed with these cars are driving, reverse, braking etc.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - OBJECTS
• In real-world an entity that has state and its behavior is known as an object.
• In terms of object-oriented programming, software objects also have a state and behavior.

For Example:
• A Car is an object. It has states (name, color,
model) and its behavior (changing gear,
applying brakes).
• A Pen is an object. Its name is Parker; color is
silver etc. known as its state. It is used to
write, so writing is its behavior.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - OBJECTS
• An object can be defined as an instance of a class, and there can
be multiple instances of a class in a program.
• An Object contains both the data and the function, which
operates on the data.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - ENCAPSULATION

• Encapsulation is the technique used to implement abstraction in object-oriented


programming. Encapsulation is used for access restriction to class members and methods.
• Enclosing one or more details from outside world (Private) through access rights.
• Other objects don’t have direct access to this state. Instead, they can only call a list of public
functions — called methods
• The object manages its own state via methods — and no other class can touch it unless
explicitly allowed.
• If you want to communicate with the object, you should use the methods provided.
• But (by default), you can’t change the state

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - Encapsulation

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - Encapsulation
• The “state” of the cat is the private variables mood, hungry and energy. It also has a private
method meow(). It can call it whenever it wants, the other classes can’t tell the cat when to
meow.
• What they can do is defined in the public methods sleep(), play() and feed().
• Each of them modifies the internal state somehow and may invoke meow(). Thus, the binding
between the private state and public methods is made.
• This is encapsulation.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - ABSTRACTION
• Abstraction can be thought of as a natural extension of encapsulation
• Abstraction is the concept of hiding the internal details (implementation) and describing things in
simple terms.
• Revealing relevant/necessary information and hiding the unwanted information is abstraction.
• Object-oriented design, programs are often extremely large.
• And separate objects communicate with each other a lot. So maintaining a large codebase like this
for years — with changes along the way — is difficult.
• Abstraction is a concept aiming to ease this problem
EXAMPLE
• In a mobile phone, dialing a number would call some method internally which will concatenate the
numbers and displays it on screen but, we don’t know what is happening internally.
• When you tap on the call option, it is sending signals to other person’s mobile(whom you are trying
to call) but we are unaware of it’s implementation.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - ABSTRACTION
• You interact with your phone by using only a few buttons. But implementation details are hidden.
• Only a short set of actions are known.
• Implementation changes —
for example, a software
update — rarely affect the
abstraction you use.

Cell phones are complex. But using them is simple.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - POLYMORPHISM
• Polymorphism means “many shapes” in Greek.
• Polymorphism is the concept where an object behaves differently in different situations.
• Performing a job in different ways.(One to many)
• Polymorphism gives a way to use a class exactly like its parent so there’s no confusion with mixing types. But
each child class keeps its own methods as they are.
• For example, in English, the verb run has a different meaning if you use it with a laptop, a foot race,
and business. Here, we understand the meaning of run based on the other words used along with it.The same
also applied to Polymorphism.
EXAMPLE
• We click photographs and record videos using the camera in a mobile phone.
• Various brands have a plethora of camera modes in a mobile like: split camera/panaroma/slow-mo.
• The basic purpose is to click/record, so the functionality of camera is the same in every mobile, whereas the
modes enable you to use your camera in different ways.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - POLYMORPHISM

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - INHERITANCE
• Inheritance is the object oriented programming concept where an object is based on another
object
• Inheritance is the mechanism of code reuse.
• The object that is getting inherited is called superclass and the object that inherits the
superclass is called subclass.
Example:
• The basic purpose of using a mobile phone is communication.
• There are several brands in mobiles. So, the brands of a mobile are using this basic
functionality(communication) by extending the mobile class functionality and adding their
own new features to their respective brands.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - INHERITANCE

By Inheriting each class adds


only what is necessary for it
while reusing common logic
with the parent classes

A private teacher is a type of teacher. And any teacher is a type of Person.


SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
1. Which of the following best defines a class?
a) Parent of an object
b) Instance of an object
c) Blueprint of an object
d) Scope of an object

2. Which Feature of OOP illustrated the code reusability?


a) Polymorphism
b) Abstraction
c) Encapsulation
d) Inheritance

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept

3. Which language does not support all 4 types of inheritance?


a) C++
b) Java
c) Kotlin
d) Small Talk

4. Why Java is Partially OOP language?


a) It supports usual declaration of primitive data types
b) It doesn’t support all types of inheritance
c) It allows code to be written outside classes
d) It does not support pointers

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept

5. Which concept of OOP is false for C++?


a) Code can be written without using classes
b) Code must contain at least one class
c) A class must have member functions
d) At least one object should be declared in code

6. Which of the two features match each other?


a) Inheritance and Encapsulation
b) Encapsulation and Polymorphism
c) Encapsulation and Abstraction
d) Abstraction and Polymorphism

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
7. Which feature allows open recursion, among the following?
a) Use of this pointer
b) Use of pointers
c) Use of pass by value
d) Use of parameterized constructor

8. Class is pass by _______


a) Value
b) Reference
c) Value or Reference, depending on program
d) Copy

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
9. Size of a class is :
a) Sum of size of all the variables declared inside the class
b) Sum of size of all the variables along with inherited variables in the class
c) Size of largest size of variable
d) Classes doesn’t have any size

10. Which class can have member functions without their implementation?
a) Default class
b) String class
c) Template class
d) Abstract class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
11. Class with main() function can be inherited (True/False)
a) True
b) False

12. Which of the following pairs are similar?


a) Class and object
b) Class and structure
c) Structure and object
d) Structure and functions

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
13. Instance of which type of class can’t be created?
a) Anonymous class
b) Nested class
c) Parent class
d) Abstract class

14. Which of the following pairs are similar?


a) Class and object
b) Class and structure
c) Structure and object
d) Structure and functions

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
15. If a function can perform more than 1 type of tasks, where the function name remains same,
which feature of OOP is used here?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction

16. If different properties and functions of a real world entity is grouped or embedded into a single
element, what is it called in OOP language?
a) Inheritance
b) Polymorphism
c) Abstraction
d) Encapsulation

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
17. How many basic features of OOP are required for a programming language to be purely
OOP?
a) 7
b) 6
c) 5
d) 4

18. The feature by which one object can interact with another object is:
a) Data transfer
b) Data Binding
c) Message Passing
d) Message reading

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
19. The feature by which one object can interact with another object is:
a) Data transfer
b) Data Binding
c) Message Passing
d) Message reading
20.Exception handling is feature of OOP. (True/False)
a) True
b) False

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MODULE 1 – Session 3

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Variables

• Variable is a piece of memory that can contain a data value.


• A variable thus has a data type
• Variables are typically used to store information
• This can be any kind of information ranging from texts, codes (e.g. country codes, currency
codes etc.) to numbers, temporary results of multi step calculations etc.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Types
• In Java there are four types of variables:

1. Non-static fields - A non-static field is a variable that belongs to an object. Objects keep their
internal state in non-static fields. Non-static fields are also called instance variables, because they
belong to instances (objects) of a class.

2. Static fields - A static field is a variable that belongs to a class. A static field has the same value for
all objects that access it. Static fields are also called class variables.

3. Local variables - A local variable is a variable declared inside a method. A local variable is only
accessible inside the method that declared it

4. Parameters - A parameter is a variable that is passed to a method when the method is called.
Parameters are also only accessible inside the method that declares them.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Data Type
• A data type, in programming, is a classification that specifies,
• Which type of value a variable has
• And what type of mathematical, relational or logical operations can be applied to it without causing
an error.
• A string, for example, is a data type that is used to classify text and an integer is a data type used to classify
whole numbers.
Data Type Used for Example
String Alphanumeric characters hello world, Alice, Bob123
Integer Whole numbers 7, 12, 999
Float (floating point) Number with a decimal point 3.15, 9.06, 00.13
Character Encoding text numerically 97 (in ASCII, 97 is a lower case 'a')
Boolean Representing logical values TRUE, FALSE

• The data type defines which operations can safely be performed to create, transform and use the variable in
another computation.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Strongly Typed And Weakly Typed
• Strongly Typed :
– Variable must be declared with a data type.
– A variable cannot start off life without knowing the range of values it can hold, and
once it is declared, the data type of the variable cannot change.
– A strongly typed language requires an explicit conversion (by using the cast
operator) between related types
– Java is a strongly typed programming language
• Weakly Typed :
– Variables are not associated to specific datatype
– Weakly typed languages place no restrictions on how data types can be mixed.
– Conversions between unrelated types are implicitly allowed.
– Example : Perl

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Data Types in Java
Data types specify the type of the values stored in variable. Two types of data types in java are
1. Primitive data types: The primitive data types include Boolean, char, byte, short, int, long,
float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java - Data Types and their Range
Data Type Default Value Default size Range
boolean false 1 bit true or false
char '\u0000' 2 byte 0 to 65535
byte 0 1 byte -128 to 127
short 0 2 byte -32,768 to 32,767
31 31
int 0 4 byte -2 to 2 -1
63 63
long 0L 8 byte -2 to 2 -1
float 0.0f 4 byte 1.4e-324 to 3.4e+038
double 0.0d 8 byte 4.9e-324 to 1.8e+308

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Primitive Data Types :
There are eight primitive datatypes supported by Java. Primitive datatypes
are predefined by the language and named by a keyword. Let us now look
into the eight primitive data types in detail.

Byte :
- Byte data type is an 8-bit signed two's complement integer
- Minimum value is -128 (-2^7)
- Maximum value is 127 (inclusive)(2^7 -1)
- Default value is 0
- Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an integer.
- Example: byte a = 100, byte b = -50

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
short

- Short data type is a 16-bit signed two's complement integer


- Minimum value is -32,768 (-2^15)
- Maximum value is 32,767 (inclusive) (2^15 -1)
- Short data type can also be used to save memory as byte data type.
- A short is 2 times smaller than an integer
- Default value is 0.
- Example: short s = 10000, short r = -20000

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Int

- Int data type is a 32-bit signed two's complement integer.


- Minimum value is - 2,147,483,648 (-2^31)
- Maximum value is 2,147,483,647(inclusive) (2^31 -1)
- Integer is generally used as the default data type for integral values
unless there is a concern about memory.
- The default value is 0
- Example: int a = 100000, int b = -200000

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
long

- Long data type is a 64-bit signed two's complement


integer
- Minimum value is -9,223,372,036,854,775,808(-2^63)
- Maximum value is 9,223,372,036,854,775,807
(inclusive)(2^63 -1)
- This type is used when a wider range than int is needed
- Default value is 0L
- Example: long a = 100000L, long b = -200000L

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Float

- Float data type is a single-precision 32-bit IEEE 754


floating point
- Float is mainly used to save memory in large arrays of
floating point numbers
- Default value is 0.0f
- Float data type is never used for precise values such as
currency
- Example: float f1 = 234.5f

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
double

- double data type is a double-precision 64-bit IEEE 754


floating point
- This data type is generally used as the default data type for
decimal values, generally the default choice
- Double data type should never be used for precise values
such as currency
- Default value is 0.0d
- Example: double d1 = 123.4

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Boolean

- boolean data type represents one bit of information


- There are only two possible values: true and false
- This data type is used for simple flags that track
true/false conditions
- Default value is false
- Example: boolean one = true

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Char

- char data type is a single 16-bit Unicode


character
- Minimum value is '\u0000' (or 0)
- Maximum value is '\uffff' (or 65,535 inclusive)
- Char data type is used to store any character
- Example: char letterA = 'A'

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Reference Datatypes :
Reference variables are created using defined constructors of the classes.
They are used to access objects. These variables are declared to be of a
specific type that cannot be changed. For example, Employee, Puppy, etc.

Class objects and various type of array variables come under reference
datatype.

Default value of any reference variable is null.

A reference variable can be used to refer any object of the declared type or
any compatible type.
Example: Animal animal = new Animal("giraffe");

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Literals :
A literal is a source code representation of a fixed value.
They are represented directly in the code without any computation.
Literals can be assigned to any primitive type variable.

For example −
byte a = 68;
char a = 'A';

byte, int, long, and short can be expressed in decimal(base 10),


hexadecimal(base 16) or octal(base 8) number systems as well.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Points to Remember:
• All numeric data types are signed (+/-).
• The size of data types remain the same on all platforms (standardized)
• Char data type in Java is 2 bytes because it uses UNICODE character set. By virtue of it, Java
supports internationalization.
• UNICODE is a character set which covers all known scripts and language in the world

Literals
• Literals are used to indicate simple values in your Java programs
• Different kinds of Literals in java are,
• numbers
• characters
• strings
• boolean values

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1. Numbers
Byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or
octal(base 8) number systems as well.
• byte a = 68;
• char a = 'A'
• int decimal = 100;
• int octal = 0144;
• int hexa = 0x64;
• int binary = 0b1111;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Characters and String
• String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes.
• Examples of string literals are −
"Hello World"
"two\nlines"
"\"This is in quotes\""
• Character literals are expressed by a single character surrounded by single quotes: ’a’, ’#’,
’3’, and so on. Characters are stored as 16-bit Unicode characters
• String and char types of literals can contain any Unicode characters.
• For example −
char a = '\u0001';
String a = "\u0001";

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Boolean literals
Boolean literals consist of the keywords true and false. These keywords can be used anywhere
you need a test or as the only possible values for Boolean variables.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Literals :
A literal is a source code representation of a fixed value.
They are represented directly in the code without any computation.
Literals can be assigned to any primitive type variable.

For example −
byte a = 68;
char a = 'A';

byte, int, long, and short can be expressed in decimal(base 10),


hexadecimal(base 16) or octal(base 8) number systems as well.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Prefix 0 is used to indicate octal, and prefix 0x indicates
hexadecimal when using these number systems for literals.

For example −
int decimal = 100;
int octal = 0144;
int hexa = 0x64;

String literals in Java are specified like they are in most other
languages by enclosing a sequence of characters between a pair of
double quotes. Examples of string literals are −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
"Hello World"
"two\nlines"
"\"This is in quotes\““

String and char types of literals can contain any Unicode characters.

For example −
char a = '\u0001';
String a = "\u0001";

Java language supports few special escape sequences for String and char
literals as well. They are −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
. Notation Character represented

\n Newline (0x0a)

\r Carriage return (0x0d)

\f Formfeed (0x0c)

\b Backspace (0x08)

\s Space (0x20)

\t tab

\" Double quote

\' Single quote

\\ backslash

\ddd Octal character (ddd)

\uxxxx Hexadecimal UNICODE character


(xxxx)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
A variable provides us with named storage that our programs can
manipulate. Each variable in Java has a specific type, which
determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of
operations that can be applied to the variable.

You must declare all variables before they can be used. Following is
the basic form of a variable declaration −

data type variable [ = value][, variable [ = value] ...] ;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Here data type is one of Java's datatypes and variable is the name of the
variable. To declare more than one variable of the specified type, you can use
a comma-separated list.

Following are valid examples of variable declaration and initialization in


Java −

Example
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization byte
B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
This chapter will explain various variable types available in Java Language.
There are three kinds of variables in Java −
1. Local variables
2. Instance variables
3. Class/Static variables

Local Variables :
- Local variables are declared in methods, constructors, or blocks.
- Local variables are created when the method, constructor or block is
entered and the variable will be destroyed once it exits the method,
constructor, or block.
- Access modifiers cannot be used for local variables.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
- Local variables are visible only within the declared method,
constructor, or block.
- Local variables are implemented at stack level internally.
- There is no default value for local variables, so local variables
should be declared and an initial value should be assigned before the
first use.

Example :
Here, age is a local variable. This is defined inside pupAge() method
and its scope is limited to only this method.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}}
This will produce the following result −

Output :
Puppy age is: 7

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
Following example uses age without initializing it, so it would give an error at
the time of compilation.
public class Test {
public void pupAge() {
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
} public static void main(String args[]) {
Test test = new Test();
test.pupAge(); } }
This will produce the following error while compiling it −
Output :
Test.java:4:variable number might not have been initialized age = age + 7; ^ 1
error
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Instance Variables :
- Instance variables are declared in a class, but outside a method, constructor
or any block.
- When a space is allocated for an object in the heap, a slot for each instance
variable value is created.
- Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
- Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that must
be present throughout the class.
- Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
- The instance variables are visible for all methods, constructors and block in
the class. Normally, it is recommended to make these variables private
(access level). However, visibility for subclasses can be given for these
variables with the use of access modifiers.

- Instance variables have default values. For numbers, the default value is 0,
for Booleans it is false, and for object references it is null. Values can be
assigned during the declaration or within the constructor.

- Instance variables can be accessed directly by calling the variable name


inside the class. However, within static methods (when instance variables are
given accessibility), they should be called using the fully qualified
name. ObjectReference.VariableName.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
import java.io.*;
public class Employee { // this instance variable is visible for any
child class.
public String name; // salary variable is visible in Employee class
only.
private double salary; // The name variable is assigned in the
constructor.
public Employee (String empName) {
name = empName; } // The salary variable is assigned a value.
public void setSalary(double empSal) {
salary = empSal; }

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
// This method prints the employee details.
public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary); }
public static void main(String args[]) {
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}}
This will produce the following result −
Output :
name : Ransika salary :1000.0

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Class/Static Variables :
- Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
-
There would only be one copy of each class variable per class, regardless of
how many objects are created from it.

- Static variables are rarely used other than being declared as constants. -
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.

- Static variables are created when the program starts and destroyed when
the program stops.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Class/Static Variables :

- Static variables can be accessed by calling with the class


name ClassName.VariableName.

- When declaring class variables as public static final, then variable


names (constants) are all in upper case. If the static variables are not
public and final, the naming syntax is the same as instance and local
variables.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
import java.io.*;
public class Employee
{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[])
{
salary = 1000; System.out.println(DEPARTMENT + "average salary:"
+ salary);
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
This will produce the following result −

Output :
Development average salary:1000

Note − If the variables are accessed from an outside class, the


constant should be accessed as Employee.DEPARTMENT

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Example:
Add Two Numbers

class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}

Output:
20

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Example:
Widening

class Simple{
public static void main(String[] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output:
10
10.0

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Example:
Overflow

class Simple{
public static void main(String[] args){
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}
}
Output:
130
-126
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Example:
Narrowing (Typecasting)

class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}
}
Output:
10.5
10
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Example:
Adding Lower Type

class Simple{
public static void main(String[] args){
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
System.out.println(c);
}
}
Output:
20

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Q) Why char uses 2 byte in java and what is \u0000 ?

It is because java uses Unicode system not ASCII code system.

The \u0000 is the lowest range of Unicode system.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Unicode System
• Unicode is a universal international standard character encoding that is capable
of representing most of the world's written languages.

• Why java uses Unicode System?


Before Unicode, there were many language standards: ASCII (American Standard
Code for Information Interchange) for the United States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for chinese, and so on.

lowest value:\u0000
highest value:\uFFFF

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQs
1. Which code fragment correctly assign a numeric literal?
A) byte b1 = b1011;
B) byte b2 = 1011b;
C) byte b3 = 0b1001;
D) byte b4 = 0xb001;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Given the fragment:
public class MathFun {
public static void main(String[] args) {
int number1 = 0b0111;
int number2 = 0111_000;
System.out.println("Number1: " + number1); OPTIONS :
A) Number1: 7
System.out.println("Number2: " + number1); Number2: 7
} B) Number1: 7
Number2: 111_000
} C) Number1: 0b0111
Number2: 0111000
What is the result? D) Compilation fails.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. class Main {
public static void main(String args[]) {
int t;
System.out.println(t);
}
} OPTIONS
(A) 0
(B) garbage value
(C) compiler error
(D) runtime error

4. Automatic type conversion in Java takes place when

OPTIONS :
A. Two type are compatible and size of destination type is shorter than source type.
B. Two type are compatible and size of destination type is equal of source type.
C. Two type are compatible and size of destination type is larger than source type.
D. All of the above

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5. What is the output of the following program?
class A{
public static void main(String args[]){
byte b;
int i = 258;
double d = 325.59;
b = (byte) i;
System.out.print(b);
i = (int) d;
System.out.print(i);
OPTIONS
b = (byte) d; A. 258 325 325
System.out.print(b); B. 258 326 326
} C. 2 325 69
} D. Error
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. What is the output of the following program?
public class Test{
public static void main(String [] a){
Scanner s= new Scanner(System.in);
int a=s.nextInt();
String str=s.nextLine(); INPUT :
5
System.out.println(a+” “+str);
Hello
}
OPTIONS :
} a) Hello
b) 5 Hello
c) 5
d) 5Hello

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7. What will be output of the following program code?
public class Test{
public static void main(String[] a){
short x = 10;
x = x*5;
System.out.print(x); OPTIONS :
A. 50
} B. 10
} C. Compilation Error
D. None of these

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. The following program:
public class Test{
static boolean isOK;
public static void main(String args[]){
System.out.print(isOK);
}
} OPTIONS :
A. Prints true
B. Prints false
C. Will not compile as boolean is not initialized
D. Will not compile as boolean can never be static

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. What will be the output of the program?
class Equals
{
public static void main(String [] args)
{
int x = 100;
double y = 100.1;
boolean b = (x = y); /* Line 7 */
OPTIONS :
System.out.println(b); A. true
} B. false
C. Compilation fails
} D. An exception is thrown at runtime

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. What is the output for the below code ?
1. public class Test{
2. public static void main(String[] args){
3. int i = 010;
4. int j = 07;
5. System.out.println(i); OPTIONS :
A. 8 7
6. System.out.println(j); B. 10 7
7. } C. Compilation fails with an error at line 3
D. Compilation fails with an error at line 5
8. } E. None of these

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. Select from among the following character escape code which is not
available in Java. OPTIONS :
A. t
B. r
C. a
12. .Determine output: D. \
public class Test{ E. “
public static void main(String... args){
int a=5 , b=6, c=7;
System.out.println("Value is "+ b + c);
System.out.println(a + b + c);
System.out.println("String " + (b+c));
} OPTIONS :
} A. Value is 67 18 String 13
B. Value is 13 18 String 13
C. Value is 13 18 String
D. Compilation fails

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
13. In Java, the word true is................
OPTIONS :
A. A Java keyword
B. A Boolean literal
C. Same as value 1
D. Same as value 0

14. What will be the output of the program?


class Equals
{
public static void main(String [] args)
{
int x = 100;
double y = 100.1;
boolean b = (x = y); /* Line 7 */ OPTIONS :
System.out.println(b); A. true
} B. false
} C. Compilation fails
D. An exception is thrown at runtime

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
15. Find the error:
public class Test{
public static void main(String [] args){
int a=55; \\line1
float b=45.59; \\line2
double c=67.4567; \\line3
System.out.println(a+“ ”+b+” “+c); \\line4
}
} OPTIONS :
a) line1
b) line2
c) line3
d) line 4

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
16. What is the valid data type for variable “a” to print “Hello World”?
switch(a)
{ OPTIONS:
System.out.println("Hello World"); a) int and float
b) byte and short
} c) char and long
d) byte and char

17. How many primitive data types are there in Java?


OPTIONS:
A. 6
B. 7
C. 8
D. 9

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
18. In Java byte, short, int and long all of these are
OPTIONS :
A. signed
B. unsigned
C. Both of the above
D. None of these

19. What is the range of data type byte in Java? OPTIONS :


A. -128 to 127
B. -32768 to 32767
C. -2147483648 to 2147483647
D. None of the mentioned

20. Which of these literals can be contained in a data type float variable?
OPTIONS :
A.1.7e-308
B. 3.4e-038
C. 1.7e+308
D. 3.4e-050

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Mcqs-Answers

1.C 11.C
2.A 12.A
3.C 13.B
4.C 14.C
5.C 15.B
6.C 16.D
7.C 17.C
8.B 18.A
9.C 19.A
10.A 20.B

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1. What is the range of data type short in Java?

A. -128 to 127
B. -32768 to 32767
C. -2147483648 to 2147483647
D. None of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. What is the range of data type byte in Java?

A. -128 to 127
B. -32768 to 32767
C. -2147483648 to 2147483647
D. None of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. An expression involving byte, int, and literal
numbers is promoted to which of these?

A. int
B. long
C. byte
D. float

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Which of these literals can be contained in a
data type float variable?

A. 1.7e-308
B. 3.4e-038
C. 1.7e+308
D. 3.4e-050

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5. Which data type value is returned by all
transcendental math functions?

A. int
B. float
C. double
D. long

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. What is the numerical range of a char in
Java?

A. -128 to 127
B. 0 to 256
C. 0 to 32767
D. 0 to 65535

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7. Which of these coding types is used for data
type characters in Java?

A. ASCII
B. ISO-LATIN-1
C. UNICODE
D. None of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. Which of these values can a boolean variable
contain?

A. True & False


B. 0 & 1
C. Any integer value.
D. Both a & b

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. Which of these occupy first 0 to 127 in Unicode
character set used for characters in Java?

A. ASCII
B. ISO-LATIN-1
C. None of the mentioned
D. Both a & b

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. Which one is a valid declaration of a
boolean?

A. boolean b1 = 1;
B. boolean b2 = ‘false’;
C. boolean b3 = false;
D. boolean b4 = ‘true’

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. What is the output of this program?
class mainclass {
public static void main(String args[])
{
char a = 'A';
a++;
System.out.print((int)a);
}
}
A. 66
B. 67
C. 65
D. 64

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
12. What is the output of this program?
class mainclass {
public static void main(String args[])
{
boolean var1 = true;
boolean var2 = false;
if (var1)
System.out.println(var1);
else
System.out.println(var2);
}
}
A. 0
B. 1
C. true
D. false © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD.
13. Which of the following is smallest integer
data type ?

A. int
B. byte
C. short
D. long

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
14. Integer Data type does not include following
primitive data type ?

A. long
B. byte
C. short
D. double

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
15. Which of the following data types comes
under floating data types ?

A. int
B. double
C. long
D. byte

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
16. Range of Byte Data Type is
____________.

A. -128 to 128
B. -127 to 127
C. -127 to 128
D. -128 to 127

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
17. Which of the following data type(s) can store
64 bit Value.

A. boolean
B. int
C. float
D. long

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
18. Short data type has a minimum value of
____ .

A. -32,768
B. -32,767
C. 32768
D. 32767

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
19.Default value of variable having boolean data type
is ______.

A. True
B. False
C. Null
D. Garbage

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
20. What will be the output of the program?

class Main {
public static void main(String args[]) {
int t;
System.out.println(t);
}}

A. 0
B. garbage value
C. compiler error
D. runtime error

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
21. What will be the output of the program?

class Test {
public static void main(String[] args) {
for(int i = 0; 0; i++) {
System.out.println("Hello");
break;
}}}

A. Hello
B. Empty Output
C. Compiler error
D. Runtime error

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
22.What will be the output of the program?

class mainclass {
public static void main(String args[]) {
boolean var1 = true;
boolean var2 = false;
if (var1) System.out.println(var1);
else System.out.println(var2);
}}

A. 0
B. 1
C. true
D. false

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
23. Predict the output of the following program.

class Test {
public static void main(String[] args) {
Double object = new Double("2.4");
int a = object.intValue();
byte b = object.byteValue();
float d = object.floatValue();
double c = object.doubleValue();
System.out.println(a + b + c + d );
}}
A. 8
B. 8.8
C. 8.800000095367432
D. 8.0
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
24. What is the output of this program?

class average {
public static void main(String args[]) {
double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};
double result;
result = 0;
for (int i = 0; i<6; ++i)
result = result + num[i];
System.out.print(result/6);
}}
A. 16.34
B. 16.566666644
C. 16.46666666666667
D. 16.46666666666666
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
25. Which of the following are legal lines of Java code?
1. int w = (int)888.8;
2. byte x = (byte)100L;
3. long y = (byte)100;
4. byte z = (byte)100L;

A. 1 and 2
B. 2 and 3
C. 3 and 4
D. All statements are correct

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answers
1. B 14. D
2. A 15. B
3. A 16. D
4. B 17. D
5. C 18. A
6. D 19. B
7. C 20. C
8. A 21. C
9. D 22. C
10. C 23. C
11. A 24. C
12. C 25. D
13. B

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thank you

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Programming in Java

Class in Java

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 1 of Resources Pvt. Ltd.
Programming in Java
Definition Of class

• A class is a collection of data members & methods or the process of


binding data members and associated methods in a single unit is
called class
• The purpose of classes concept is that to develop user define
(programmer) data type.
• Use class keyword to define class
• Whenever define a class there is no memory space is created for
data members and methods of class whose memory space will be
created when we create an object.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 2 of Resources Pvt. Ltd.
Programming in Java
• Data members (variables) of class also knows as attribute, field or
properties.
• Methods are also known as accessories or behavior.
• In oops we have two types of methods they are:-
o Member Method
o Non Member Method
• Member Method is method that’s write inside the class
• Non member method is method that’s write outside the class
• Java Programming language only allow the Member method.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 3 of Resources Pvt. Ltd.
Programming in Java
Block diagram class

• Block Diagram

Class Name

Data Member

Methods

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 4 of Resources Pvt. Ltd.
Programming in Java
Syntax & Example of Class
• Syntax
Class class name
{
Data members;
Members Methods;
}

Example:

Class abc
{
Int a;
Void show()
{
System.out.printin(a);
}
}
SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 5 of Resources Pvt. Ltd.
Programming in Java
Syntax class
• Syntax
Class class name
{
Data members;
Members Methods;
}

Example:

Class abc
{
Int a;
Void show()
{
System.out.printin(a);
}
}
SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 6 of Resources Pvt. Ltd.
Programming in Java
Inner class

• Inner class nothing but creating class inside the class


• Inner classes are a security mechanism in Java. We know
a class cannot be associated with the access modifier private, but if
we have the class as a member of other class, then the inner
class can be made private. And this is also used to access the
private members of a class

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 7 of Resources Pvt. Ltd.
Programming in Java
Syntax of Inner Class
• Syntax
class Outer_Demo {
class Inner_Demo {
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 8 of Resources Pvt. Ltd.
Programming in Java
Example of Inner Class
• Example:
class Outer_Demo { int num;
class Inner_Demo {
public void print()
{ System.out.println("This is an inner class");
}
}
void display_Inner()
{
Inner_Demo inner = new Inner_Demo(); inner.print();
}
}
public class My_class
{ public static void main(String args[])
{Outer_Demo outer = new Outer_Demo();
method. outer.display_Inner();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 9 of Resources Pvt. Ltd.
Programming in Java
Method-local Inner Class

• Write Method inside the inner class that’s called Local Inner Class
• A method-local inner class can be instantiated only within the
method where the inner class is defined

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 10 of Resources Pvt. Ltd.
Programming in Java
Method local inner class Example
public class Outerclass
{
// instance method of the outer class
void my_Method()
{
int num = 23;
// method-local inner class
class MethodInner_Demo
{
public void print()
{
System.out.println("This is method inner class "+num);
} // end of inner class
} // Accessing the inner class
MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}
public static void main(String args[])
{
Outerclass outer = new Outerclass();
outer.my_Method();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 11 of Resources Pvt. Ltd.
Programming in Java
Static Inner class

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

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 12 of Resources Pvt. Ltd.
Programming in Java
Example of Static Inner Class

class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 13 of Resources Pvt. Ltd.
Programming in Java
Anonymous inner class

• A class that have no name is known as anonymous inner class in


java. It should be used if you have to override method of class or
interface. Java Anonymous inner class can be created by two ways:
• Class (may be abstract or concrete).
• Interface

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 14 of Resources Pvt. Ltd.
Programming in Java
Example of Static Inner Class

class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 15 of Resources Pvt. Ltd.
Programming in Java
Anonymous inner class example

abstract class Person{


abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 16 of Resources Pvt. Ltd.
Programming in Java
MCQ

1. Which of these class is superclass of every class in Java?


a) String class
b) Object class
c) Abstract class
d) ArrayList class
2. Predict the output of following Java program?
class Test {
int i;
}
class Main {
public static void main(String args[]) {
Test t;
System.out.println(t.i);
compiler error}
a) 0
b) garbage value
c) compiler error
d) runtime error

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 17 of Resources Pvt. Ltd.
Programming in Java
3. Which of these class relies upon its subclasses for complete implementation of its methods?
a) Object class
b) abstract class
c) ArrayList class
d) None of the mentioned
4. Which of these keywords are used to define an abstract class?
a) abst
b) abstract
c) Abstract
d) abstract class

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 18 of Resources Pvt. Ltd.
Programming in Java
5. Which of these class relies upon its subclasses for complete implementation of its methods?
a) Object class
b) abstract class
c) ArrayList class
d) None of the mentioned
6. Which of the following is an invalid declaration for the main method in java program?
a) public static void main (String [ ] args)
B) public static strictfp void main(String args[ ])
C) final static public void main (String args[ ])
D) All are Correct

7. A top level class may have which one of the following access modifiers?
a) package
b) private
C) protected
d) public

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 19 of Resources Pvt. Ltd.
Programming in Java
8. A subclass is also called as
a) inner class
b) nested class
c) derived class
d) hidden class
9. Which of the following is not a wrapper class?
a) Vector
b) character
c) Boolean
d) Integer
10. 7 Which of the following method is used to initialize the instance variable of a class

a) class
b) public
C) Constructor
d) Destructor

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 20 of Resources Pvt. Ltd.
Programming in Java

Object & object cloning in java

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 1 of Resources Pvt. Ltd.
Programming in Java
Definition Of Object

• Instance of a class is known as object


• We know that when we define a class there is no memory space is
created for the methods & data member but whose memory space
will be created when we create an object with respect to class.
• Creating as object is nothing but allocating sufficient memory space
for data member and methods of class. We use new keyword to
allocate memory space.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 2 of Resources Pvt. Ltd.
Programming in Java
Syntax & Example of Object
• Syntax
Class name object name= new classname();

Example:

DemoVit object = new DemoVit();

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 3 of Resources Pvt. Ltd.
Programming in Java
Definition Of Object Cloning

• Object cloning refers to creation of exact copy of an object. It


creates a new instance of the class of current object and initializes
all its fields with exactly the contents of the corresponding fields of
this object
• Clone() is used

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 4 of Resources Pvt. Ltd.
Programming in Java
Syntax Object Cloning

• Class name objectname=new classname();


• Class name Object2=objectname.clone();

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 5 of Resources Pvt. Ltd.
Programming in Java
Example Object Cloning
public class Main
{
public static void main(String args[]) throws
CloneNotSupportedException
{
Test2 t1 = new Test2();
t1.a = 10;
t1.b = 20;
t1.c.x = 30;
t1.c.y = 40;

Test2 t2 = (Test2)t1.clone();

// Creating a copy of object t1 and passing


// it to t2
t2.a = 100;

// Change in primitive type of t2 will not


// be reflected in t1 field
t2.c.x = 300;

// Change in object type field will be


// reflected in both t2 and t1(shallow copy)
System.out.println(t1.a + " " + t1.b + " " +
t1.c.x + " " + t1.c.y);
System.out.println(t2.a + " " + t2.b + " " +
t2.c.x + " " + t2.c.y);
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 6 of Resources Pvt. Ltd.
OPERATORS IN JAVA

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introduction
• They are symbols which used to perform operations.
For e.g.,
+, -, /, x etc.
• There are several operators used in java, they are
1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Unary operators
6. Shift operators
7. Bitwise operators
8. Ternary operators

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Arithmetic Operators
• They are used to perform arithmetic operations. They are,

Symbol Operators Example Description

+ addition a+b Gives the sum as output


operator e.g., 10+5 e.g., 15
- subtraction a-b Gives the difference as output
operator e.g., 10-5 e.g., 5
/ division operator a/b Gives as quotient as output
e.g., 10/5 e.g., 2
* multiplication a*b Gives the product as output
operator e.g., 10*5 e.g., 50
% modulus a%b Gives the remainder as output
operator e.g., 10%5 e.g., 0

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
-

Example:-
class Test{
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
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Logical operator
• Used to perform logical operations

Symbol Name Description

&& Logical AND Returns true if both statements


are true
|| Logical OR Returns true if one of the
statements is true
! Logical NOT Reverse the result, returns false
if the result is true

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example
class Test{
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(b<a&a<c);//true & true = true
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Relational Operators
• Used to compare two values

Symbol Name Example


== Equal to a==b
!= Not equal to a!=b
> greater than a>b
< less than a<b
>= Greater than or equal to a>=b
<= Less than or equal to a<=b

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Assignment Operators
• Used to assign values to variables
e.g.,
int x=10;
Here we are assigning the value 10 to the variable x.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Symbol Example Same as
= a=5 a=5
+= a += 5 a = a+5
-= a -= 5 a = a-5
*= a *= 5 a = a*5
/= a /= 5 a = a/5
%= a %= 5 a = a%5
&= a &= 5 a = a&5
|= a |=5 a = a|5
^= a^= 5 a = a^5
>>= a>>=5 a=a>>5

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
.,

Unary operators
• Requires only one operand
• Used to perform the following operations
1. Incrementing/decrementing a value by one
2. Negating an expression
3. Inverting the value of a boolean

e.g., x=20;
x++// here x =x+1, so output will be 21
x--//here x = x+1, so output will be 19

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Increment Operator
This is of two types
1. Pre-increment:- value increments first then result is computed
2. Post-increment:- value is first used for computing then increment will happen
Decrement Operator
This is of two types
1. Pre-decrement:- value decrements first then result is taken
2. Post-decrement:- value is first used for computing then decrements it

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Predict the Output
class Test{
public static void main(String args[]){
int x=20;
System.out.println(x++);//20 (21)
System.out.println(++x);//22
System.out.println(x--);//22 (21)
System.out.println(--x);//20
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
Output
20
22
22
20

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Predict the Output

int j=0;
for(int i=0; i<=5;i+)
{
j=j++;
System.out.println(j);
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
Output
0
0
0
0

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Shift Operators
• Used to shift the bits of a number to left or right side
• This is same as multiplying or dividing the number with two.

Symbol Description
>> Shifts the bits of the number to the right
<< Shifts the bits of the number to the left
>>> Unsigned right shift operator
<<< Unsigned left shift operator

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Bitwise operators
• used to perform manipulation of individual bits of a number

Symbol(Name) Description
| (Bitwise OR) returns bit by bit OR of input values
& (Bitwise AND) returns bit by bit AND of input values
^ (Bitwise XOR) returns bit by bit XOR of input values
~ (Bitwise Compliment) returns the one’s compliment representation of
the input value

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1
Predict the output
class Test {
public static void main(String args[]) {
int x = -4;
System.out.println(x>>1);
int y = 4;
System.out.println(y>>1);
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
-2
2

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2
Which of the following operators can operate on a boolean variable?
1. &&
2. ==
3. ?:
4. +=
a) 1&4
b) 3&2
c) 1,2&4
d) 1,2&3

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
d) 1,2&3

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ3
Which of these have highest precedence?
a) ()
b) ++
c) *
d) >>

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
a) ()

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
THANKYOU

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Basic IO Streams

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The java.io package contains nearly every class you might ever need to perform
input and output (I/O) in Java. All these streams represent an input source and
an output destination. The stream in the java.io package supports many data
such as primitives, object, localized characters, etc.
Stream

A stream can be defined as a sequence of data. There are two kinds of Streams −
1. InPutStream − The InputStream is used to read data from a source.
2. OutPutStream − The OutputStream is used for writing data to a
destination.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Byte Streams :

Java byte streams are used to perform input and output of 8-bit
bytes. Though there are many classes related to byte streams but the
most frequently used classes
are, FileInputStream and FileOutputStream. Following is an
example which makes use of these two classes to copy an input file
into an output file

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example:
import java.io.*; while ((c = in.read()) != -1) {
public class CopyFile { out.write(c);
public static void main(String args[]) }}
throws IOException { finally {
FileInputStream in = null; if (in != null) {
FileOutputStream out = null; in.close();
try { }
in = new FileInputStream("input.txt"); if (out != null) {
out = new out.close();
FileOutputStream("output.txt");
}}}}
int c;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Now let's have a file input.txt with the following content −
This is test for copy file.

As a next step, compile the above program and execute it, which will
result in creating output.txt file with the same content as we have in
input.txt. So let's put the above code in CopyFile.java file and do the
following −
$javac CopyFile.java
$java CopyFile

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Character Streams :

Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for
16-bit unicode. Though there are many classes related to character streams
but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes
to copy an input file (having unicode characters) into an output file .

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
import java.io.*; int c;
public class CopyFile { while ((c = in.read()) != -1) { out.write(c);
public static void main(String args[]) }}
throws IOException { finally {
FileReader in = null; if (in != null) {
FileWriter out = null; in.close();
try { }
in = new FileReader("input.txt"); if (out != null) {
out = new FileWriter("output.txt"); out.close();
}}}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Now let's have a file input.txt with the following content -
This is test for copy file.

As a next step, compile the above program and execute it, which will
result in creating output.txt file with the same content as we have in
input.txt. So let's put the above code in CopyFile.java file and do the
following −

$javac CopyFile.java
$java CopyFile

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Standard Streams :

All the programming languages provide support for standard I/O


where the user's program can take input from a keyboard and then
produce an output on the computer screen. If you are aware of C or
C++ programming languages, then you must be aware of three
standard devices STDIN, STDOUT and STDERR. Similarly, Java
provides the following three standard streams −
Standard Input − This is used to feed the data to user's program
and usually a keyboard is used as standard input stream and
represented as System.in.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Standard Output − This is used to output the data produced by
the user's program and usually a computer screen is used for
standard output stream and represented as System.out.
Standard Error − This is used to output the error data produced
by the user's program and usually a computer screen is used for
standard error stream and represented as System.err.
Following is a simple program, which
creates InputStreamReader to read standard input stream until
the user types a "q" −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
import java.io.*; do {
public class ReadConsole { c = (char) cin.read();
public static void main(String args[]) System.out.print(c);
throws IOException { }
InputStreamReader cin = null; while(c != 'q');
try { }
cin = new finally {
InputStreamReader(System.in); if (cin != null) {
System.out.println("Enter characters,
'q' to quit."); cin.close();
char c; }}}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Let's keep the above code in ReadConsole.java file and try to compile and
execute it as shown in the following program. This program continues to
read and output the same character until we press 'q' −

$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Reading and Writing Files:

As described earlier, a stream can be defined as a sequence of data.


The InputStream is used to read data from a source and
the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
-

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The two important streams
are FileInputStream and FileOutputStream, which would be discussed
in this tutorial.

FileInputStream :
This stream is used for reading data from the files. Objects
can be created using the keyword new and there are several types of
constructors available.

Following constructor takes a file name as a string to create an input stream


object to read the file −

InputStream f = new FileInputStream("C:/java/hello");

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Following constructor takes a file object to create an input stream
object to read the file. First we create a file object using File()
method as follows −

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);

Once you have InputStream object in hand, then there is a list of


helper methods which can be used to read to stream or to do other
operations on the stream.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Sr.No. Method & Description

public void close() throws IOException{} : This method closes the file output stream. Releases
any system resources associated with the file.
Throws an IOException.
protected void finalize()throws This method cleans up the connection to the file.
IOException {} : Ensures that the close method of this file output
stream is called when there are no more references
to this stream. Throws an IOException.

public int read(int r)throws IOException{} : This method reads the specified byte of data from
the InputStream. Returns an int. Returns the next
byte of data and -1 will be returned if it's the end of
the file.

public int read(byte[] r) throws This method reads r.length bytes from the input
IOException{} : stream into an array. Returns the total number of
bytes read. If it is the end of the file, -1 will be
returned.
public int available() throws
SMART TRAINING IOException{}
RESOURCES INDIA PVT. LTD. Gives the number of bytes ©
that
2018can beTraining
SMART readResources
from this
Pvt. Ltd.
There are other important input streams available, for more detail you can refer
to the following links −
ByteArrayInputStream
DataInputStream

FileOutputStream :
FileOutputStream is used to create a file and write data into it. The
stream would create a file, if it doesn't already exist, before opening it for
output.

Here are two constructors which can be used to create a FileOutputStream


object.

Following constructor takes a file name as a string to create an input stream


object to write the file −
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to


write the file. First, we create a file object using File() method as follows −

File f = new File("C:/java/hello"); OutputStream f = new


FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper
methods, which can be used to write to stream or to do other operations on
the stream.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
S.No Method & Description

public void close() throws This method closes the file output stream.
IOException{} : Releases any system resources associated
with the file. Throws an IOException.
protected void finalize()throws This method cleans up the connection to the
IOException {} : file. Ensures that the close method of this file
output stream is called when there are no
more references to this stream. Throws an
IOException.

public void write(int w)throws This methods writes the specified byte to the
IOException{} : output stream.

public void write(byte[] w) : Writes w.length bytes from the mentioned


byte array to the OutputStream.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
There are other important output streams available, for more detail
you can refer to the following links −

- ByteArrayOutputStream
- DataOutputStream

Example
Following is the example to demonstrate InputStream and
OutputStream −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example:
import java.io.*; InputStream is = new
public class fileStreamTest { FileInputStream("test.txt");
public static void main(String args[]) { int size = is.available();
try { for(int i = 0; i < size; i++) {
byte bWrite [] = {11,21,3,40,5}; System.out.print((char)is.read() + " ");
OutputStream os = new }
FileOutputStream("test.txt"); is.close();
for(int x = 0; x < bWrite.length ; x++) { }
os.write( bWrite[x] ); catch (IOException e) {
} os.close(); System.out.print("Exception");
}}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The above code would create file test.txt and would write given
numbers in binary format. Same would be the output on the stdout
screen.

File Navigation and I/O :


There are several other classes that we would be
going through to get to know the basics of File Navigation and I/O.

File Class
FileReader Class
FileWriter Class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Directories in Java :
A directory is a File which can contain a list of
other files and directories. You use File object to create directories,
to list down files available in a directory. For complete detail, check a
list of all the methods which you can call on File object and what are
related to directories.

Creating Directories :
There are two useful File utility methods,
which can be used to create directories −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
- The mkdir( ) method creates a directory, returning true on
success and false on failure. Failure indicates that the path specified
in the File object already exists, or that the directory cannot be
created because the entire path does not exist yet.

- The mkdirs() method creates both a directory and all the parents
of the directory.

Following example creates "/tmp/user/java/bin" directory −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :

import java.io.File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname); // Create directory now.
d.mkdirs();
}}

Compile and execute the above code to create "/tmp/user/java/bin".

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Listing Directories :
You can use list( ) method provided by File object to list
down all the files and directories available in a directory as follows −
Example
import java.io.File;
public class ReadDir {
public static void main(String[] args) {
File file = null;
String[] paths;
try { // create new file object
file = new File("/tmp");

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
// array of files and directory
paths = file.list(); // for each name in the path array
for(String path:paths) { // prints filename and directory name
System.out.println(path);
}}
catch (Exception e) { // if any error occurs
e.printStackTrace();
}}}

This will produce the following result based on the directories and files available
in your /tmp directory −

Output
test1.txt test2.txt ReadDir.java ReadDir.class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ’S

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1. The …………………… package contains a large
number of stream classes that provide capabilities for
processing all types of data.
A) java.awt
B) java.io
C) java.util
D) java.net

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Which of these is used to perform all input &
output operations in Java?
A. streams
B. Variables
C. classes
D. Methods

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. What does AWT stands for?

A. All Window Tools


B. All Writing Tools
C. Abstract Window Toolkit
D. Abstract Writing Toolkit

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Which of these is a type of stream in Java?

A. Integer stream
B. Short stream
C. Byte stream
D. Long stream

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5. Which of these classes are used by character
streams for input and output operations?

A. InputStream
B. Writer
C. ReadStream
D. InputOutputStream

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. Which of these class is used to read from byte
array?

A. InputStream.
B. BufferedInputStream.
C. ArrayInputStream.
D. ByteArrayInputStream.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7. Which exception is thrown by read() method?

A. IOException
B. InterruptedException
C. SystemException
D. SystemInputException

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. Which of these is used to read a string from
the input stream?

A. get()
B. getLine()
C. read()
D. readLine()

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. Which of these class is used to read
characters and strings in Java from console?

A. BufferedReader
B. StringReader
C. BufferedStreamReader
D. InputStreamReader

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. Which of these classes are used by Byte
streams for input and output operation?

A. InputStream
B. InputOutputStream
C. Reader
D. All of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. Which of these class is implemented by
FilterInputStream class?

A. InputStream
B. BufferedInputStream
C. FileInputStream
D. BufferedFileInputStream

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
12. Which of these class contains the methods
print() & println()?

A. System
B. System.out
C. BUfferedOutputStream
D. PrintStream

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
13. Which of these methods can be used to
writing console output?

A. print()
B. println()
C. write()
D. All of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
14. Which of these class is used to create an
object whose character sequence is mutable?

A. String()
B. StringBuffer()
C. Both of the mentioned
D. None of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
15. Which of these method of class StringBuffer
is used to reverse sequence of characters?

A. reverse()
B. reverseall()
C. Reverse()
D. reverseAll()

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
16. Which of these classes are used by character
streams output operations?

A. InputStream
B. Writer
C. ReadStream
D. InputOutputStream

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
17. Which of the following statement is correct?

A. reverse() method reverses all characters.


B. reverseall() method reverses all characters.
C. replace() method replaces first occurrence of a
character in invoking string with another character.
D. replace() method replaces last occurrence of a
character in invoking string with another character.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
18. Which of these classes are used by Byte
streams for input and output operation?

A. InputStream
B. InputOutputStream
C. Reader
D. All of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
19. Which of these method of FileReader class is
used to read characters from a file?
a) read()
b) scanf()
c) get()
d) getInteger()

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
20. What will be the output of the following Java program?

import java.io.*;
class Chararrayinput
{
public static void main(String[] args)
{
String obj = "abcdef";
int length = obj.length();
char c[] = new char[length];
obj.getChars(0,length,c,0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 0, 3);
int i;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
try
{
while ((i = input1.read()) != -1)
{
System.out.print((char)i);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
a) abc
b) abcd
c) abcde
d) abcdef

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answers
1. B 11. C
2. A 12. D
3. C 13. D
4. C 14. B
5. B 15. A
6. D 16. B
7. A 17. A
8. A 18. A
9. D 19. A
10. A 20. D

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thank You

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Basic IO Streams

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The java.io package contains nearly every class you might ever need to perform
input and output (I/O) in Java. All these streams represent an input source and
an output destination. The stream in the java.io package supports many data
such as primitives, object, localized characters, etc.
Stream

A stream can be defined as a sequence of data. There are two kinds of Streams −
1. InPutStream − The InputStream is used to read data from a source.
2. OutPutStream − The OutputStream is used for writing data to a
destination.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Byte Streams :

Java byte streams are used to perform input and output of 8-bit
bytes. Though there are many classes related to byte streams but the
most frequently used classes
are, FileInputStream and FileOutputStream. Following is an
example which makes use of these two classes to copy an input file
into an output file

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example:
import java.io.*; while ((c = in.read()) != -1) {
public class CopyFile { out.write(c);
public static void main(String args[]) }}
throws IOException { finally {
FileInputStream in = null; if (in != null) {
FileOutputStream out = null; in.close();
try { }
in = new FileInputStream("input.txt"); if (out != null) {
out = new out.close();
FileOutputStream("output.txt");
}}}}
int c;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Now let's have a file input.txt with the following content −
This is test for copy file.

As a next step, compile the above program and execute it, which will
result in creating output.txt file with the same content as we have in
input.txt. So let's put the above code in CopyFile.java file and do the
following −
$javac CopyFile.java
$java CopyFile

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Character Streams :

Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for
16-bit unicode. Though there are many classes related to character streams
but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes
to copy an input file (having unicode characters) into an output file .

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
import java.io.*; int c;
public class CopyFile { while ((c = in.read()) != -1) { out.write(c);
public static void main(String args[]) }}
throws IOException { finally {
FileReader in = null; if (in != null) {
FileWriter out = null; in.close();
try { }
in = new FileReader("input.txt"); if (out != null) {
out = new FileWriter("output.txt"); out.close();
}}}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Now let's have a file input.txt with the following content -
This is test for copy file.

As a next step, compile the above program and execute it, which will
result in creating output.txt file with the same content as we have in
input.txt. So let's put the above code in CopyFile.java file and do the
following −

$javac CopyFile.java
$java CopyFile

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Standard Streams :

All the programming languages provide support for standard I/O


where the user's program can take input from a keyboard and then
produce an output on the computer screen. If you are aware of C or
C++ programming languages, then you must be aware of three
standard devices STDIN, STDOUT and STDERR. Similarly, Java
provides the following three standard streams −
Standard Input − This is used to feed the data to user's program
and usually a keyboard is used as standard input stream and
represented as System.in.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Standard Output − This is used to output the data produced by
the user's program and usually a computer screen is used for
standard output stream and represented as System.out.
Standard Error − This is used to output the error data produced
by the user's program and usually a computer screen is used for
standard error stream and represented as System.err.
Following is a simple program, which
creates InputStreamReader to read standard input stream until
the user types a "q" −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
import java.io.*; do {
public class ReadConsole { c = (char) cin.read();
public static void main(String args[]) System.out.print(c);
throws IOException { }
InputStreamReader cin = null; while(c != 'q');
try { }
cin = new finally {
InputStreamReader(System.in); if (cin != null) {
System.out.println("Enter characters,
'q' to quit."); cin.close();
char c; }}}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Let's keep the above code in ReadConsole.java file and try to compile and
execute it as shown in the following program. This program continues to
read and output the same character until we press 'q' −

$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Reading and Writing Files:

As described earlier, a stream can be defined as a sequence of data.


The InputStream is used to read data from a source and
the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
-

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The two important streams
are FileInputStream and FileOutputStream, which would be discussed
in this tutorial.

FileInputStream :
This stream is used for reading data from the files. Objects
can be created using the keyword new and there are several types of
constructors available.

Following constructor takes a file name as a string to create an input stream


object to read the file −

InputStream f = new FileInputStream("C:/java/hello");

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Following constructor takes a file object to create an input stream
object to read the file. First we create a file object using File()
method as follows −

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);

Once you have InputStream object in hand, then there is a list of


helper methods which can be used to read to stream or to do other
operations on the stream.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Sr.No. Method & Description

public void close() throws IOException{} : This method closes the file output stream. Releases
any system resources associated with the file.
Throws an IOException.
protected void finalize()throws This method cleans up the connection to the file.
IOException {} : Ensures that the close method of this file output
stream is called when there are no more references
to this stream. Throws an IOException.

public int read(int r)throws IOException{} : This method reads the specified byte of data from
the InputStream. Returns an int. Returns the next
byte of data and -1 will be returned if it's the end of
the file.

public int read(byte[] r) throws This method reads r.length bytes from the input
IOException{} : stream into an array. Returns the total number of
bytes read. If it is the end of the file, -1 will be
returned.
public int available() throws
SMART TRAINING IOException{}
RESOURCES INDIA PVT. LTD. Gives the number of bytes ©
that
2018can beTraining
SMART readResources
from this
Pvt. Ltd.
There are other important input streams available, for more detail you can refer
to the following links −
ByteArrayInputStream
DataInputStream

FileOutputStream :
FileOutputStream is used to create a file and write data into it. The
stream would create a file, if it doesn't already exist, before opening it for
output.

Here are two constructors which can be used to create a FileOutputStream


object.

Following constructor takes a file name as a string to create an input stream


object to write the file −
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to


write the file. First, we create a file object using File() method as follows −

File f = new File("C:/java/hello"); OutputStream f = new


FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper
methods, which can be used to write to stream or to do other operations on
the stream.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
S.No Method & Description

public void close() throws This method closes the file output stream.
IOException{} : Releases any system resources associated
with the file. Throws an IOException.
protected void finalize()throws This method cleans up the connection to the
IOException {} : file. Ensures that the close method of this file
output stream is called when there are no
more references to this stream. Throws an
IOException.

public void write(int w)throws This methods writes the specified byte to the
IOException{} : output stream.

public void write(byte[] w) : Writes w.length bytes from the mentioned


byte array to the OutputStream.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
There are other important output streams available, for more detail
you can refer to the following links −

- ByteArrayOutputStream
- DataOutputStream

Example
Following is the example to demonstrate InputStream and
OutputStream −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example:
import java.io.*; InputStream is = new
public class fileStreamTest { FileInputStream("test.txt");
public static void main(String args[]) { int size = is.available();
try { for(int i = 0; i < size; i++) {
byte bWrite [] = {11,21,3,40,5}; System.out.print((char)is.read() + " ");
OutputStream os = new }
FileOutputStream("test.txt"); is.close();
for(int x = 0; x < bWrite.length ; x++) { }
os.write( bWrite[x] ); catch (IOException e) {
} os.close(); System.out.print("Exception");
}}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The above code would create file test.txt and would write given
numbers in binary format. Same would be the output on the stdout
screen.

File Navigation and I/O :


There are several other classes that we would be
going through to get to know the basics of File Navigation and I/O.

File Class
FileReader Class
FileWriter Class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Directories in Java :
A directory is a File which can contain a list of
other files and directories. You use File object to create directories,
to list down files available in a directory. For complete detail, check a
list of all the methods which you can call on File object and what are
related to directories.

Creating Directories :
There are two useful File utility methods,
which can be used to create directories −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
- The mkdir( ) method creates a directory, returning true on
success and false on failure. Failure indicates that the path specified
in the File object already exists, or that the directory cannot be
created because the entire path does not exist yet.

- The mkdirs() method creates both a directory and all the parents
of the directory.

Following example creates "/tmp/user/java/bin" directory −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :

import java.io.File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname); // Create directory now.
d.mkdirs();
}}

Compile and execute the above code to create "/tmp/user/java/bin".

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Listing Directories :
You can use list( ) method provided by File object to list
down all the files and directories available in a directory as follows −
Example
import java.io.File;
public class ReadDir {
public static void main(String[] args) {
File file = null;
String[] paths;
try { // create new file object
file = new File("/tmp");

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
// array of files and directory
paths = file.list(); // for each name in the path array
for(String path:paths) { // prints filename and directory name
System.out.println(path);
}}
catch (Exception e) { // if any error occurs
e.printStackTrace();
}}}

This will produce the following result based on the directories and files available
in your /tmp directory −

Output
test1.txt test2.txt ReadDir.java ReadDir.class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ’S

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1. The …………………… package contains a large
number of stream classes that provide capabilities for
processing all types of data.
A) java.awt
B) java.io
C) java.util
D) java.net

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Which of these is used to perform all input &
output operations in Java?
A. streams
B. Variables
C. classes
D. Methods

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. What does AWT stands for?

A. All Window Tools


B. All Writing Tools
C. Abstract Window Toolkit
D. Abstract Writing Toolkit

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Which of these is a type of stream in Java?

A. Integer stream
B. Short stream
C. Byte stream
D. Long stream

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5. Which of these classes are used by character
streams for input and output operations?

A. InputStream
B. Writer
C. ReadStream
D. InputOutputStream

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. Which of these class is used to read from byte
array?

A. InputStream.
B. BufferedInputStream.
C. ArrayInputStream.
D. ByteArrayInputStream.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7. Which exception is thrown by read() method?

A. IOException
B. InterruptedException
C. SystemException
D. SystemInputException

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. Which of these is used to read a string from
the input stream?

A. get()
B. getLine()
C. read()
D. readLine()

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. Which of these class is used to read
characters and strings in Java from console?

A. BufferedReader
B. StringReader
C. BufferedStreamReader
D. InputStreamReader

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. Which of these classes are used by Byte
streams for input and output operation?

A. InputStream
B. InputOutputStream
C. Reader
D. All of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. Which of these class is implemented by
FilterInputStream class?

A. InputStream
B. BufferedInputStream
C. FileInputStream
D. BufferedFileInputStream

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
12. Which of these class contains the methods
print() & println()?

A. System
B. System.out
C. BUfferedOutputStream
D. PrintStream

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
13. Which of these methods can be used to
writing console output?

A. print()
B. println()
C. write()
D. All of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
14. Which of these class is used to create an
object whose character sequence is mutable?

A. String()
B. StringBuffer()
C. Both of the mentioned
D. None of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
15. Which of these method of class StringBuffer
is used to reverse sequence of characters?

A. reverse()
B. reverseall()
C. Reverse()
D. reverseAll()

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
16. Which of these classes are used by character
streams output operations?

A. InputStream
B. Writer
C. ReadStream
D. InputOutputStream

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
17. Which of the following statement is correct?

A. reverse() method reverses all characters.


B. reverseall() method reverses all characters.
C. replace() method replaces first occurrence of a
character in invoking string with another character.
D. replace() method replaces last occurrence of a
character in invoking string with another character.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
18. Which of these classes are used by Byte
streams for input and output operation?

A. InputStream
B. InputOutputStream
C. Reader
D. All of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
19. Which of these method of FileReader class is
used to read characters from a file?
a) read()
b) scanf()
c) get()
d) getInteger()

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
20. What will be the output of the following Java program?

import java.io.*;
class Chararrayinput
{
public static void main(String[] args)
{
String obj = "abcdef";
int length = obj.length();
char c[] = new char[length];
obj.getChars(0,length,c,0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 0, 3);
int i;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
try
{
while ((i = input1.read()) != -1)
{
System.out.print((char)i);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
a) abc
b) abcd
c) abcde
d) abcdef

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answers
1. B 11. C
2. A 12. D
3. C 13. D
4. C 14. B
5. B 15. A
6. D 16. B
7. A 17. A
8. A 18. A
9. D 19. A
10. A 20. D

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thank You

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
JAVA
IF-ELSE STATEMENTS
SWITCH STATEMENT
LOOPING STATEMENTS
BASIC PROBLEMS
Java If-else Statement

The Java if statement is used to test the condition. It checks boolean

condition: true or false.

There are various types of if statement in Java.


• if statement
• if-else statement
• if-else-if ladder
• nested if statement
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
}
Java if Statement
//Java Program to demonstate 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");
}
}
}
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.

• Syntax:

if(condition){
//code if condition is true
}else{
//code if condition is false
}
Java if-else Statement

//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");
}
}
}
Leap Year Example:

• A year is leap, if it is divisible by 4 and 400. But, not by 100.

public class LeapYearExample {


public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){

System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
}
}
}
Using Ternary Operator

• We can also use ternary operator (? :) to perform the task of if...else statement.
It is a shorthand way to check the condition. If the condition is true, the result
of ? is returned. But, if the condition is false, the result of : is returned.

public class IfElseTernaryExample {


public static void main(String[] args) {
int number=13;
//Using ternary operator
String output=(number%2==0)?"even number":"odd number";
System.out.println(output);
}
}
Java if-else-if ladder Statement

• The if-else-if ladder statement executes one condition from multiple


statements.
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.

public class IfElseIfExample {


public static void main(String[] args) {
int marks=65;

if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Program to check POSITIVE, NEGATIVE or ZERO:

public class PositiveNegativeExample {


public static void main(String[] args) {
int number=-13;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}
Java Nested if statement

• The nested if statement represents the if


block within another if block. Here, the
inner if block condition executes only
when outer if block condition is true.

• Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Java Nested if statement

//Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample2 {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} else{
System.out.println("You are not eligible to donate blood");
}
} else{
System.out.println("Age must be greater than 18");
}
} }
JAVA SWITCH STATEMENT
Java Switch Statement

• The Java switch statement executes one statement from multiple


conditions. It is like if-else-if ladder statement. The switch statement
works with byte, short, int, long, enum types, String and some wrapper
types like Byte, Short, Int, and Long. Since Java 7, you can use strings in
the switch statement.

• In other words, the switch statement tests the equality of a variable


against multiple values.
Points to Remember

• There can be one or N number of case values for a switch expression.


• The case value must be of switch expression type only. The case value must be
literal or constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-time
error.
• The Java switch expression must be of byte, short, int, long (with its Wrapper type),
enums and string.
• Each case statement can have a break statement which is optional. When control
reaches to the break statement, it jumps the control after the switch expression. If a
break statement is not found, it executes the next case.
• The case value can have a default label which is optional.
Syntax:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//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");
}
}
}
Switch practice problems

• Program to check Vowel or Consonant:

• Finding Month Example:


Java Switch Statement is fall-through
//break statement
public class SwitchExample2 {
public static void main(String[] args) {
int number=20;
//switch expression with int value
switch(number){
//switch cases without break statements
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Java Switch Statement with String
//statement with String
public class SwitchStringExample {
public static void main(String[] args) {
//Declaring String variable
String levelString="Expert";
int level=0;
//Using String in Switch expression
switch(levelString){
//Using String Literal in Switch case
case "Beginner": level=1;
break;
case "Intermediate": level=2;
break;
case "Expert": level=3;
break;
default: level=0;
break;
}
System.out.println("Your Level is: "+level);
}
}
Java Nested Switch Statement

//Java Program to demonstrate the use of Java Nested Switch


public class NestedSwitchExample {
public static void main(String args[])
{
//C - CSE, E - ECE, M - Mechanical
char branch = 'C';
int collegeYear = 4;
switch( collegeYear )
{
case 1:
System.out.println("English, Maths, Science");
break;
Java Nested Switch Statement
case 2:
switch( branch )
{
case 'C':
System.out.println("Operating System, Java, Data Structure");

break;
case 'E':
System.out.println("Micro processors, Logic switching theory");

break;
case 'M':
System.out.println("Drawing, Manufacturing Machines");
break;
}
break;
Java Nested Switch Statement
case 3:
switch( branch )
{
case 'C':
System.out.println("Computer Organization, MultiMedia");
break;
case 'E':
System.out.println("Fundamentals of Logic Design, Microel
ectronics");
break;
case 'M':
System.out.println("Internal Combustion Engines, Mechani
cal Vibration");
break;
}
break;
Java Nested Switch Statement
case 4:
switch( branch )
{
case 'C':
System.out.println("Data Communication and Networks,
MultiMedia");
break;
case 'E':
System.out.println("Embedded System, Image Processin
g");
break;
case 'M':
System.out.println("Production Technology, Thermal Engi
neering");
break;
}
break;
}
}
}
JAVA FOR LOOP
Loops in Java

• In programming languages, loops are used to execute a set of


instructions/functions repeatedly when some conditions become true.
There are three types of loops in Java.

• for loop
• while loop
• do-while loop
Java for loop

• The Java for loop is used to iterate a part of the program several times.
If the number of iteration is fixed, it is recommended to use for loop.

• There are three types of for loops in java.


• Simple For Loop
• For-each or Enhanced For Loop
• Labeled For Loop
Java Simple For Loop

• A simple for loop is the same as C/C++. We can initialize the variable, check condition
and increment/decrement value. It consists of four parts:

• Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is an
optional condition.
• Condition: It is the second condition which is executed each time to test the condition of
the loop. It continues execution until the condition is false. It must return boolean value
either true or false. It is an optional condition.
• Statement: The statement of the loop is executed each time until the second condition is
false.
• Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
Java Simple For Loop

Syntax:

for(initialization;condition;incr/decr){
//statement or code to be executed
}
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Java Nested For Loop

• If we have a for loop inside the another loop, it is known as nested for
loop. The inner loop executes completely whenever outer loop
executes.
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
Pyramid Example 1:
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Pyramid Example 2:

public class PyramidExample2 {


public static void main(String[] args) {
int term=6;
for(int i=1;i<=term;i++){
for(int j=term;j>=i;j--){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Java for-each Loop

• The for-each loop is used to traverse array or collection in java. It is easier to use
than simple for loop because we don't need to increment value and use subscript
notation.

• It works on elements basis not index. It returns element one by one in the defined
variable.

• Syntax:

for(Type var:array){
//code to be executed
}
Java for-each Loop

//Java For-each loop example which prints the


//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Java Labeled For Loop

• We can have a name of each Java for loop. To do so, we use label before
the for loop. It is useful if we have nested for loop so that we can
break/continue specific for loop.

• Usually, break and continue keywords breaks/continues the innermost


for loop only.
labelname:
for(initialization;condition;incr/decr){

//code to be executed
}
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
• If you use break bb;, it will break inner loop only which is the default
behavior of any loop.

public class LabeledForExample2 {


public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}
Java Infinitive For Loop

• If you use two semicolons ;; in the for loop, it will be infinitive for loop.

• Syntax:

for(;;){
//code to be executed
}
//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println("infinitive loop");
}
}
}
Java While Loop

The Java while loop is used to iterate a part of the program several times.
If the number of iteration is not fixed, it is recommended to use while loop.

Syntax:

while(condition){
//code to be executed
}
Java While Loop

public class WhileExample {


public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Java Infinitive While Loop

If you pass true in the while loop, it will be infinitive while loop.

Syntax:

while(true){
//code to be executed
}
Java Infinitive While Loop

public class WhileExample2 {


public static void main(String[] args) {
while(true){
System.out.println("infinitive while loop");
}
}
}
Java do-while Loop

The Java do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.

The Java do-while loop is executed at least once because condition is checked after loop
body.

Syntax:

do{
//code to be executed
}while(condition);
Java Infinitive do-while Loop

If you pass true in the do-while loop, it will be infinitive do-while loop.

Syntax:

do{
//code to be executed
}while(true);
Java Infinitive do-while Loop

public class DoWhileExample2 {


public static void main(String[] args) {
do{
System.out.println("infinitive do while loop");
}while(true);
}
}
BREAK / CONTINUE
Java Break Statement

• When a break statement is encountered inside a loop, the loop is


immediately terminated and the program control resumes at the next
statement following the loop.

• The Java break statement is used to break loop or switch statement. It


breaks the current flow of the program at specified condition. In case of
inner loop, it breaks only inner loop.

• We can use Java break statement in all types of loops such as for loop,
while loop and do-while loop.
Java Break Statement with Loop

//Java Program to demonstrate the use of break statement


//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Java Break Statement with Inner Loop
//Java Program to illustrate the use of break statement
//inside an inner loop
public static void main(String[] args) {
public class BreakExample2 {
//outer loop
for(int i=1;i<=3;i++){
//inner loop
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using break statement inside the inner loop
break;
}
System.out.println(i+" "+j);
}
}
}
}
Java Break Statement with Labeled For Loop
//Java Program to illustrate the use of continue statement
//with label inside an inner loop to break outer loop
public class BreakExample3 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using break statement with label
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Java Break Statement in while loop
//Java Program to demonstrate the use of break statement
//inside the while loop.
public class BreakWhileExample {
public static void main(String[] args) {
//while loop
int i=1;
while(i<=10){
if(i==5){
//using break statement
i++;
break;//it will break the loop
}
System.out.println(i);
i++;
}
}
}
Java Break Statement in do-while loop
//Java Program to demonstrate the use of break statement
//inside the Java do-while loop.
public class BreakDoWhileExample {
public static void main(String[] args) {
//declaring variable
int i=1;
//do-while loop
do{
if(i==5){
//using break statement
i++;
break;//it will break the loop
}
System.out.println(i);
i++;
}while(i<=10);
}
}
Java Continue Statement

• The continue statement is used in loop control structure when you need to
jump to the next iteration of the loop immediately. It can be used with for
loop or while loop.

• The Java continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition. In case of an inner loop, it continues the inner loop only.

• We can use Java continue statement in all types of loops such as for loop,
while loop and do-while loop.
Java Continue Statement Example

//Java Program to demonstrate the use of continue statement


//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}
Java Continue Statement with Inner Loop
//Java Program to illustrate the use of continue statement
//inside an inner loop
public class ContinueExample2 {
public static void main(String[] args) {
//outer loop
for(int i=1;i<=3;i++){
//inner loop
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using continue statement inside inner loop
continue;
}
System.out.println(i+" "+j);
}
}
}
}
Java Continue Statement with Labeled For Loop
//Java Program to illustrate the use of continue statement
//with label inside an inner loop to continue outer loop
public class ContinueExample3 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using continue statement with label
continue aa;
}
System.out.println(i+" "+j);
}
}
}
}
Java Continue Statement in while loop
//Java Program to demonstrate the use of continue statement
//inside the while loop.
public class ContinueWhileExample {
public static void main(String[] args) {
//while loop
int i=1;
while(i<=10){
if(i==5){
//using continue statement
i++;
continue;//it will skip the rest statement
}
System.out.println(i);
i++;
}
}
}
Java Continue Statement in do-while loop
//Java Program to demonstrate the use of continue statement
//inside the Java do-while loop.
public class ContinueDoWhileExample {
public static void main(String[] args) {
//declaring variable
int i=1;
//do-while loop
do{
if(i==5){
//using continue statement
i++;
continue;//it will skip the rest statement
}
System.out.println(i);
i++;
}while(i<=10);
}
}
Decision Making

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Decision making structures have one or more conditions to be
evaluated or tested by the program, along with a statement or
statements that are to be executed if the condition is determined to
be true, and optionally, other statements to be executed if the
condition is determined to be false.

Following is the general form of a typical decision making structure


found in most of the programming languages −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
-

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
If Statement :
An if statement consists of a Boolean expression
followed by one or more statements.

Syntax :
Following is the syntax of an if statement −
if(Boolean_expression)
{
// Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the
if statement will be executed. If not, the first set of code after the end of the if
statement (after the closing curly brace) will be executed.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :

public class Test {


public static void main(String args[]) {
int x = 10;
if( x < 20 ) {
System.out.print("This is if statement");
}}}
This will produce the following result −

Output :
This is if statement.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
If-else Statement :
An if statement can be followed by an optional else statement, which
executes when the Boolean expression is false.

Syntax :
Following is the syntax of an if...else statement −
if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false }

If the boolean expression evaluates to true, then the if block of code will be
executed, otherwise else block of code will be executed.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Flow Diagram :

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :

public class Test {


public static void main(String args[]) {
int x = 30;
if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}}}
This will produce the following result −

Output :
This is else statement

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The if...else if...else Statement :
An if statement can be followed by an optional else
if...else statement, which is very useful to test various conditions using single
if...else if statement.

When using if, else if, else statements there are a few points to keep in mind.

- An if can have zero or one else's and it must come after any else if's.

- An if can have zero to many else if's and they must come before the else.

- Once an else if succeeds, none of the remaining else if's or else's will be
tested.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Syntax :

Following is the syntax of an if...else statement −


if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is true.
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :

public class Test {


public static void main(String args[]) {
int x = 30;
if( x == 10 ) {
System.out.print("Value of X is 10");
}
else if( x == 20 ) {
System.out.print("Value of X is 20");
}
else if( x == 30 )
{

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
System.out.print("Value of X is 30");
}
else {
System.out.print("This is else statement");
}}}

This will produce the following result −

Output :
Value of X is 30

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Nested if statement :
It is always legal to nest if-else statements which means you can
use one if or else if statement inside another if or else if statement.

Syntax :
The syntax for a nested if...else is as follows −
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}}

You can nest else if...else in the similar way as we have


nested if statement.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :

public class Test {


public static void main(String args[]) {
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}}}}
This will produce the following result −

Output :
X = 30 and Y = 10

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Switch statement :
A switch statement allows a variable to be tested for
equality against a list of values. Each value is called a case, and the
variable being switched on is checked for each case.

Syntax :
The syntax of enhanced for loop is −
switch(expression) {
case value : // Statements
break; // optional

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
case value : // Statements
break; // optional
// You can have any number of case statements.
default : // Optional
// Statements }

The following rules apply to a switch statement −

- The variable used in a switch statement can only be integers, convertable


integers (byte, short, char), strings and enums.

- You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
- The value for a case must be the same data type as the variable in the switch
and it must be a constant or a literal.

- When the variable being switched on is equal to a case, the statements


following that case will execute until a break statement is reached.

- When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.

- Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.

- A switch statement can have an optional default case, which must appear at
the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Flow Diagram :

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
public class Test {
public static void main(String args[]) {
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade) {
case 'A' : System.out.println("Excellent!");
break;
case 'B' :
case 'C' : System.out.println("Well done");
break;
case 'D' : System.out.println("You passed");

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
case 'F' : System.out.println("Better try again");
break;
default : System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}}

Compile and run the above program using various command line arguments.
This will produce the following result −

Output :
Well done
Your grade is C

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java programming language provides following types of decision
making statements. Click the following links to check their detail.

Statement Description

if statement An if statement consists of a boolean


expression followed by one or more
statements.
if...else statement An if statement can be followed by an
optional else statement, which executes
when the boolean expression is false.

Nested if statement You can use one if or else if statement inside


another if or else if statement(s).

Switch statement A switch statement allows a variable to be


tested for equality against a list of values.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The ? : Operator :

We have covered conditional operator ? : in the previous chapter which


can be used to replace if...else statements. It has the following general form

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement
of the colon.
To determine the value of the whole expression, initially exp1 is evaluated.
If the value of exp1 is true, then the value of Exp2 will be the value of the
whole expression.
If the value of exp1 is false, then Exp3 is evaluated and its value becomes the
value of the entire expression.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Loop Control

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
There may be a situation when you need to execute a block of code
several number of times. In general, statements are executed
sequentially: The first statement in a function is executed first,
followed by the second, and so on.

Programming languages provide various control structures that


allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of


statements multiple times and following is the general form of a loop
statement in most of the programming languages −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
-

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
while Loop :
A while loop statement in Java programming language
repeatedly executes a target statement as long as a given condition is
true.

Syntax :
The syntax of a while loop is −

while(Boolean_expression) {
// Statements
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Here, statement(s) may be a single statement or a block of
statements. The condition may be any expression, and true is any
non zero value.

When executing, if the boolean_expression result is true, then the


actions inside the loop will be executed. This will continue as long as
the expression result is true.

When the condition becomes false, program control passes to the


line immediately following the loop.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Flow Diagram :

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Here, key point of the while loop is that the loop might not ever run.
When the expression is tested and the result is false, the loop body
will be skipped and the first statement after the while loop will be
executed.

Example :

public class Test {


public static void main(String args[]) {
int x = 10;
while( x < 20 )
{

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}}}
This will produce the following result −

Output :
value of x : 10
value of x : 11
value of x : 12
value of x : 13

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
for loop :
A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to be executed a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax :
The syntax of a for loop is −

for(initialization; Boolean_expression; update)


{
// Statements
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Here is the flow of control in a for loop −
- The initialization step is executed first, and only once. This step allows
you to declare and initialize any loop control variables and this step ends
with a semi colon (;).
- Next, the Boolean expression is evaluated. If it is true, the body of the
loop is executed. If it is false, the body of the loop will not be executed and
control jumps to the next statement past the for loop.
- After the body of the for loop gets executed, the control jumps back up to
the update statement. This statement allows you to update any loop control
variables. This statement can be left blank with a semicolon at the end.
- The Boolean expression is now evaluated again. If it is true, the loop
executes and the process repeats (body of loop, then update step, then
Boolean expression). After the Boolean expression is false, the for loop
terminates.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Flow Diagram :

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
Following is an example code of the for loop in Java.

public class Test {


public static void main(String args[]) {
for(int x = 10; x < 20; x = x + 1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}}}

This will produce the following result −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output :

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
do while loop :
A do...while loop is similar to a while loop, except that a do...while
loop is guaranteed to execute at least one time.
Syntax :
Following is the syntax of a do...while loop −
do {
// Statements
}
while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the
statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the control jumps back up to do statement,


and the statements in the loop execute again. This process repeats until the
Boolean expression is false. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD.
Flow Diagram :

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :

public class Test {


public static void main(String args[]) {
int x = 10;
do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
while( x < 20 );
}}

This will produce the following result −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output :

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java programming language provides the following types of loop to
handle looping requirements. Click the following links to check their
detail.
Loop Description

While Loop Repeats a statement or group of


statements while a given condition is
true. It tests the condition before
executing the loop body.
For loop Execute a sequence of statements
multiple times and abbreviates the
code that manages the loop variable.
Do……. While loop Like a while statement, except that it
tests the condition at the end of the
loop body.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Loop Control Statements :
Loop control statements change
execution from its normal sequence. When execution leaves a scope,
all automatic objects that were created in that scope are destroyed.

- Java supports the following control statements. Click the following


links to check their detail.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Break statement :
The break statement in Java programming language has the
following two usages −

When the break statement is encountered inside a loop, the loop is


immediately terminated and the program control resumes at the next
statement following the loop.

It can be used to terminate a case in the switch statement (covered in the


next chapter).

Syntax :
The syntax of a break is a single statement inside any loop −
break;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Flow Diagram :

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x ); System.out.print("\n");
}}}
This will produce the following result −

Output :
10 20

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Continue statement :
The continue keyword can be used in any of the loop
control structures. It causes the loop to immediately jump to the next
iteration of the loop.

In a for loop, the continue keyword causes control to immediately jump to


the update statement.

In a while loop or do/while loop, control immediately jumps to the Boolean


expression.

Syntax:
The syntax of a continue is a single statement inside any loop −
continue;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Flow Diagram :

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue; }
System.out.print( x );
System.out.print("\n");
}}}

This will produce the following result −


Output :
10 20 40 50

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
.
Control Statement Description

Break Statement Terminates


the loop or switch statement and
transfers execution to the statement
immediately following the loop or
switch.

Continue Statement Causes the loop to skip the remainder


of its body and immediately retest its
condition prior to reiterating.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Enhanced for loop in Java :
As of Java 5, the enhanced for loop was introduced. This is mainly
used to traverse collection of elements including arrays.

Syntax :

Following is the syntax of enhanced for loop −

for(declaration : expression) { // Statements }

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Declaration − The newly declared block variable, is of a type
compatible with the elements of the array you are accessing. The
variable will be available within the for block and its value would be
the same as the current array element.

Expression − This evaluates to the array you need to loop through.


The expression can be an array variable or method call that returns
an array.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :

public class Test


{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String [] names = {"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}}}

This will produce the following result −

Output :
10, 20, 30, 40, 50, James, Larry, Tom, Lacy,

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ’S

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1. Which of these selection statements test only
for equality?
a) if
b) switch
c) if & switch
d) none of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Which of these are selection statements in
Java?
a) if()
b) for()
c) continue
d) break

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Which of the following loops will execute the
body of loop even when condition controlling
the loop is initially false?
a) do-while
b) while
c) for
d) none of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Which of these jump statements can skip
processing the remainder of the code in its body
for a particular iteration?
a) break
b) return
c) exit
d) continue

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5. Which of this statement is incorrect?
a) switch statement is more efficient than a set of
nested ifs
b) two case constants in the same switch can have
identical values
c) switch statement can only test for equality,
whereas if statement can evaluate any type of
boolean expression
d) it is possible to create a nested switch statements

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. What will be the output of the following Java program?
class selection_statements
{
public static void main(String args[])
{
int var1 = 5;
int var2 = 6;
if ((var2 = 1) == var1)
System.out.print(var2);
else
System.out.print(++var2);
}
}
a) 1
b) 2
c) 3
d) 4

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7. What will be the output of the following Java program?
class comma_operator
{
public static void main(String args[])
{
int sum = 0;
for (int i = 0, j = 0; i < 5 & j < 5; ++i, j = i + 1)
sum += i;
System.out.println(sum);
}
}
a) 5
b) 6
c) 14
d) compilation error
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. What will be the output of the following Java program?
class jump_statments
{
public static void main(String args[])
{
int x = 2;
int y = 0;
for ( ; y < 10; ++y)
{
if (y % x == 0)
continue;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
else if (y == 8)
break;
else
System.out.print(y + " ");
}
}
}
a) 1 3 5 7
b) 2 4 6 8
c) 1 3 5 7 9
d) 1 2 3 4 5 6 7 8 9

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. What will be the output of the following Java program?
class Output
{
public static void main(String args[])
{
final int a=10,b=20;
while(a<b)
{
System.out.println("Hello");
}
System.out.println("World");
}
}
a) Hello
b) run time error
c) Hello world
d) compile time error

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. What will be the output of the following Java program?
class Output
{
public static void main(String args[])
{
int a = 5;
int b = 10;
first:
{
second:
{
third:
{

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
if (a == b >> 1)
break second;
}
System.out.println(a);
}
System.out.println(b);
}
}
}
a) 5 10
b) 10 5
c) 5
d) 10

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. What would be the output of the following code snippet if variable a=10?
if(a<=0)
{
if(a==0)
{
System.out.println("1 ");
}
else
{
System.out.println("2 ");
}
}
System.out.println("3 ");
a) 1 2
b) 2 3
c) 1 3
d) 3

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
12. The while loop repeats a set of code
while the condition is not met?
a) True
b) False

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
13. What is true about a break?
a) Break stops the execution of entire program
b) Break halts the execution and forces the control
out of the loop
c) Break forces the control out of the loop and starts
the execution of next iteration
d) Break halts the execution of the loop for certain
time frame

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
14. What is true about do statement?
a) do statement executes the code of a loop at least
once
b) do statement does not get execute if condition is
not matched in the first iteration
c) do statement checks the condition at the beginning
of the loop
d) do statement executes the code more than once
always

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
15. Which of the following is used with the
switch statement?
a) Continue
b) Exit
c) break
d) do

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
16. What is the valid data type for variable “a” to print “Hello World”?

switch(a)
{
System.out.println("Hello World");
}

a) int and float


b) byte and short
c) char and long
d) byte and char

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
17. Which of the following is not a decision
making statement?
a) if
b) if-else
c) switch
d) do-while

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
18. Which of the following is not a valid jump
statement?
a) break
b) goto
c) continue
d) return

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
19. From where break statement causes an exit?
a) Only from innermost loop
b) Terminates a program
c) Only from innermost switch
d) From innermost loops or switches

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
20. Which of the following is not a valid
flow control statement?
a) exit()
b) break
c) continue
d) return

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answers
1. B 11. D
2. A 12. B
3. A 13. B
4. D 14. A
5. B 15. C
6. B 16. D
7. B 17. D
8. C 18. B
9. D 19. D
10. D 20. A

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thank You

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Pattern Programs

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Pattern Programs in Java
- Star Patterns in Java
- Numeric Patterns
- Character Patterns

Star Patterns in Java

First, let us begin with the basic and the commonly asked
pattern program in Java i.e Pyramid.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1. Pyramid Program
*
**
***
****
*****
Let’s write the java code to understand this pattern better.

public class Smart


{
public static void pyramidPattern(int n)
{
for (int i=0; i<n; i++) //outer loop for number of rows(n)
{
for (int j=n-i; j>1; j--) //inner loop for spaces
{

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
System.out.print(" "); //print space
}
for (int j=0; j<=i; j++ ) //inner loop for number of columns
{
System.out.print("* "); //print star
}
System.out.println(); //ending line after each row
}
}
public static void main(String args[]) //driver function
{
int n = 5;
pyramidPattern(n);
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Right Triangle Star Pattern

*
**
***
****
*****
Let’s write the java code to understand this pattern better.
public class Smart
{
public static void rightTriangle(int n)
{
int i, j;
for(i=0; i<n; i++) //outer loop for number of rows(n)
{
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
for(j=2*(n-i); j>=0; j--) // inner loop for spaces
{
System.out.print(" "); // printing space
}
for(j=0; j<=i; j++) // inner loop for columns
{
System.out.print("* "); // print star
}
System.out.println(); // ending line after each row
}
}
public static void main(String args[])
{
int n = 5;
rightTriangle(n);
} © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD.
3. Left Triangle Star Pattern
*
**
***
****
*****
Let’s write the java code to understand this pattern better.
public class Smart
{
public static void printStars(int n)
{
int i, j;
for(i=0; i<n; i++) //outer loop for number of rows(n)
{
for(j=2*(n-i); j>=0; j--) // inner loop for spaces
{ SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
System.out.print(" "); // printing space
}
for(j=0; j<=i; j++) // inner loop for columns
{
System.out.print("* "); // print star
}
System.out.println(); // ending line after each row
}
}
public static void main(String args[])
{
int n = 5;
printStars(n);
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Diamond Shape Pattern Program in Java
Enter the number of rows: 5
*
***
*****
*******
*********
*******
*****
***
*
Let’s write the java code to understand this pattern better.
import java.util.Scanner;
public class Smart
{
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
public static void main(String args[])
{
int n, i, j, space = 1;
System.out.print("Enter the number of rows: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
space = n - 1;
for (j = 1; j<= n; j++)
{
for (i = 1; i<= space; i++)
{
System.out.print(" ");
}
space--;
for (i = 1; i <= 2 * j - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
space = 1;
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
for (j = 1; j<= n - 1; j++)
{
for (i = 1; i<= space; i++)
{
System.out.print(" ");
}
space++;
for (i = 1; i<= 2 * (n - j) - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5. Downward Triangle Star Pattern
Enter the number of rows: 5
*****
****
***
**
*
Let’s write the java code to understand this pattern better.
import java.util.Scanner;
public class Smart
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of rows: ");

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
int rows = sc.nextInt();

for (int i= rows-1; i>=0 ; i--)


{
for (int j=0; j<=i; j++)
{
System.out.print("*" + " ");
}
System.out.println();
}
sc.close();
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. Reversed Pyramid Star Pattern
Enter the number of rows: 5
*****
****
***
**
*
Let’s write the java code to understand this pattern better.
import java.util.Scanner;
public class Smart
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows: ");

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
int rows = sc.nextInt();
for (int i= 0; i<= rows-1 ; i++)
{
for (int j=0; j<=i; j++)
{
System.out.print(" ");
}
for (int k=0; k<=rows-1-i; k++)
{
System.out.print("*" + " ");
}
System.out.println();
}
sc.close();
}
} © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD.
Numeric Pattern in Java

1. Simple number program


1
12
123
1234
12345
Let’s write the java code to understand this pattern better.
public class Smart
{
public static void printNums(int n)
{
int i, j,num;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
for(i=0; i<n; i++) // outer loop for rows
{
num=1;
for(j=0; j<=i; j++) // inner loop for rows
{
// printing num with a space
System.out.print(num+ " ");

//incrementing value of num


num++;
}

// ending line after each row


System.out.println();
}
}
public static void main(String args[])
{
int n = 5;
printNums(n);
}
} SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Number Pattern Program in java
1
23
456
7 8 9 10
11 12 13 14 15

Let’s write the java code to understand this pattern better.


import java.util.Scanner;

public class Smart


{
public static void main(String[] args) {
int i, j, k = 1;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
for (i = 1; i <= 5; i++) {
for (j = 1; j< i + 1; j++) {
System.out.print(k++ + " ");
}
System.out.println();
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Pascal’s Triangle Program in Java
1
11
121
1331
14641

Let’s write the java code to understand this pattern better.

import java.util.Scanner;
public class Smart
{
public static void main(String[] args) {
int n = 5;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
for (int i = 0; i < n; i++) {
int number = 1;
System.out.printf("%" + (n - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.printf("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Diamond Pattern Program in Java
1
212
32123
4321234
32123
212
1

Let’s write the java code to understand this pattern better.


import java.util.Scanner;
public class Smart
{
public static void main(String[] args) {
for (int i = 1; i <= 4; i++)
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
{
int n = 4;

for (int j = 1; j<= n - i; j++)


{
System.out.print(" ");
}
for (int k = i; k >= 1; k--)
{
System.out.print(k);
}
for (int l = 2; l <= i; l++)
{
System.out.print(l);
}
System.out.println();
}
for (int i = 3; i >= 1; i--)
{
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
int n = 3;
for (int j = 0; j<= n - i; j++) { System.out.print(" "); } for (int k = i; k >= 1; k--
)
{
System.out.print(k);
}
for (int l = 2; l <= i; l++)
{
System.out.print(l);
}
System.out.println();
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5. Number Pattern Programs in Java
Enter the number of rows: 5
1
22
333
4444
55555

Let’s write the java code to understand this pattern better.


import java.util.Scanner;
public class Smart
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
System.out.println("Enter the number of rows: ");
int rows = sc.nextInt();
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(i+" ");
}

System.out.println();
}
sc.close();
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. Descending order Pattern
Enter the number of rows: 5
5
54
543
5432
54321

Let’s write the java code to understand this pattern better.


import java.util.Scanner;
public class Smart
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
System.out.println("Enter the number of rows: ");

int rows = sc.nextInt();


for (int i = rows; i >= 1; i--)
{
for (int j = rows; j >= i; j--)
{
System.out.print(j+" ");
}

System.out.println();
}
sc.close();
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Alphabet/ Character Patterns in Java
1. Right Alphabetic triangle
A
AB
ABC
ABCD
ABCDE
ABCDEF

Let’s write the java code to understand this pattern better.


import java.util.Scanner;
public class Smart
{
public static void main(String[] args)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
{
int alphabet = 65;
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= i; j++)
{
System.out.print((char) (alphabet + j) + " ");
}
System.out.println();
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Alphabet/ Character Pattern Programs
A
BB
CCC
DDDD
EEEEE
FFFFFF

Let’s write the java code to understand this pattern better.


import java.util.Scanner;
public class Smart
{
public static void main(String[] args)
{

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
int alphabet = 65;
for (int i = 0; i<= 5; i++)
{
for (int j = 0; j <= i; j++)
{
System.out.print((char) alphabet + " ");
}
alphabet++;
System.out.println();
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Triangle Character Pattern Program in Java
A
AB
ABC
ABCD
ABCDE
ABCDEF

Let’s write the java code to understand this pattern better.


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

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
for (int i = 0; i <= 5; i++)
{
int alphabet = 65;
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 0; k <= i; k++)
{
System.out.print((char) (alphabet + k) + " ");
}
System.out.println();
}
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thank You

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Programming in Java

Different Types of classes in


Java

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 1 of Resources Pvt. Ltd.
Programming in Java

• A class is as important for coding in Java as it is important for us to


breathe to stay alive. You may be working with a basic class in
Java or you might be a beginner, don’t worry, I have got you all
covered. In this session on “Types of classes in Java” will help you
get in-depth knowledge about the various types of classes used
in Java programming.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 2 of Resources Pvt. Ltd.
Programming in Java
What are classes in Java?

• A class in Java is a template that is used to create and define objects, object data
types, and methods. Classes as a whole are categories and objects are items within
each category. A class declaration constitutes of the following parts:
• Modifiers
• Class name
• Keywords
• The class body within curly brackets {}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 3 of Resources Pvt. Ltd.
Programming in Java
Block diagram class

• Block Diagram

Class Name

Data Member

Methods

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 4 of Resources Pvt. Ltd.
Programming in Java
POJO Class

• POJO stands for “Plain Old Java Object”. A class which contains
only private variables and setter and getter methods to use those
variables is called POJO class. It is a pure data structure that has
fields and may override some methods from Object (e.g. equals) or
some other interface like serializable but does not have the behavior
of its own.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 5 of Resources Pvt. Ltd.
Programming in Java
Properties of POJO class –

• Public setter and getter methods are a must while writing a POJO class.
• All instance variables should be private.
• It should not extend pre-specified classes.
• It should not implement pre-specified interfaces.
• Should not contain pre-specified annotations.
• It may not have a no-argument constructor.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 6 of Resources Pvt. Ltd.
Programming in Java
Example for POJO Class
class POJO {
private int value=365;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public class Test {
public static void main(String args[]){
POJO p = new POJO();
System.out.println(p.getValue());
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 7 of Resources Pvt. Ltd.
Programming in Java
Static Class

• In Java, static is a keyword used to describe how objects are managed within the
memory. A static object belongs specifically to the class, instead of instances of
that class. The sole purpose of the class is to provide blueprints of its inherited
classes. A static class can contain static members only. You cannot create an
object for a static class.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 8 of Resources Pvt. Ltd.
Programming in Java
Example

package Intro;
public class Bank {
private static String note = "Bank";
public static class SBISavings{
public void displayOutput(){
System.out.println(" SBISaving is: " + note);
}
}
public static void main(String[] args) {
SBISavings bs = new Bank.SBISavings();
bs.displayOutput();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 9 of Resources Pvt. Ltd.
Programming in Java
Assignment

Using a Static class


to add two numbers.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 10 of Resources Pvt. Ltd.
Programming in Java
Concrete Class

• Any normal class which does not have any abstract method or a class having an
implementation for all of its methods is basically a concrete class. They cannot
have any unimplemented methods. A concrete class can extend its parent class, an
abstract class or implement an interface if it implements all their methods. It is a
complete class that can be instantiated.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 11 of Resources Pvt. Ltd.
Programming in Java
Example for concrete class

public class Concrete { // Concrete Class


static int sum(int x, int y) {
return a + b;
}
public static void main(String args[]) {
int p = sum(6, 8);
System.out.println("Sum: " + p);
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 12 of Resources Pvt. Ltd.
Programming in Java
Abstract Class

• An abstract class is declared with an abstract keyword and have zero or more
abstract methods. These classes are incomplete classes, therefore, to use an
abstract class we strictly need to extend the abstract classes to a concrete class. It
can have constructors and static methods as well. It can have final methods which
will force the subclass to keep the body of the method unhung.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 13 of Resources Pvt. Ltd.
Programming in Java

Example for Abstract class


package Intro; public class Main extends
Product{
interface X{
public static void main(String[]
int product(int x, int y); args) {
} Main ob = new
Main();
abstract class Product implements
int p = ob.product(20,
X{ 10);
public int product(int x, // print product
int y){
System.out.println("Product: " +
return x * y; p);
} }
} }

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 14 of Resources Pvt. Ltd.
Programming in Java
Final Class

• Once a variable, method or a class is declared as final, it’s value


remains the same throughout. The final keyword in a method
declaration indicates that the method cannot be overridden by any
subclasses i.e., a class that has been declared final cannot be
subclassed. This helps a lot while creating an immutable class like
the String class. A class cannot make a class immutable without
making it final.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 15 of Resources Pvt. Ltd.
Programming in Java
Example for Final Class

final class BaseClass {


void Display() {
System.out.print("This is the Display() method of BaseClass.");
}
}
class DerivedClass extends BaseClass { //Compile-time error - can't inherit final class
void Display() {
System.out.print("This is Display() method of DerivedClass.");
}
}
public class FinalClassDemo {
public static void main(String[] arg) {
DerivedClass d = new DerivedClass();
d.Display();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 16 of Resources Pvt. Ltd.
Programming in Java
Inner class

• Inner class means the class which is a member of another class.


There are four types of inner classes in java.
1) Nested Inner class
2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 17 of Resources Pvt. Ltd.
Programming in Java
1)Nested Inner class

• It can access any private instance variable of an outer class. Like


any other instance variable, we can have access modifiers private,
protected, public and default modifier.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 18 of Resources Pvt. Ltd.
Programming in Java
An Example to show demonstrate Inner class:

class Outer {
// Simple nested inner class
class Inner {
public void show() {
System.out.println("This is inside a nested class method ");
}
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 19 of Resources Pvt. Ltd.
Programming in Java
2) Method Local inner classes

An inner class can be declared within a method


of an outer class.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 20 of Resources Pvt. Ltd.
Programming in Java
Example

class Outer {
void outerMethod() {
System.out.println("This is outerMethod");
// Inner class is local to outerMethod()
class Inner {
void innerMethod() {
System.out.println("This is innerMethod");
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodDemo {
public static void main(String[] args) {
Outer x = new Outer();
x.outerMethod();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 21 of Resources Pvt. Ltd.
Programming in Java
3) Anonymous inner classes

Anonymous inner classes are declared without any name. They can be
created in two ways.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 22 of Resources Pvt. Ltd.
Programming in Java
Example for Anonymous innerclass

class Demo {
void show() {
System.out.println("This is show method of super class");
}
}
public class Main {
// An anonymous class with Demo as base class
static Demo d = new Demo() {
void show() {
super.show();
System.out.println("This is Flag1Demo class");
}
};
public static void main(String[] args) {
d.show();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 23 of Resources Pvt. Ltd.
Programming in Java
4) Static nested classes

• Static nested classes are like a static member of the outer class.

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 24 of Resources Pvt. Ltd.
Programming in Java
Example for static nested class

Assignment

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 25 of Resources Pvt. Ltd.
Programming in Java
MCQ

1. Which of these class is superclass of every class in Java?


a) String class
b) Object class
c) Abstract class
d) ArrayList class
2. Predict the output of following Java program?
class Test {
int i;
}
class Main {
public static void main(String args[]) {
Test t;
System.out.println(t.i);
compiler error}
a) 0
b) garbage value
c) compiler error
d) runtime error

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 26 of Resources Pvt. Ltd.
Programming in Java
3. Which of these class relies upon its subclasses for complete implementation of its methods?
a) Object class
b) abstract class
c) ArrayList class
d) None of the mentioned
4. Which of these keywords are used to define an abstract class?
a) abst
b) abstract
c) Abstract
d) abstract class

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 27 of Resources Pvt. Ltd.
Programming in Java
5. Which of these class relies upon its subclasses for complete implementation of its methods?
a) Object class
b) abstract class
c) ArrayList class
d) None of the mentioned
6. Which of the following is an invalid declaration for the main method in java program?
a) public static void main (String [ ] args)
B) public static strictfp void main(String args[ ])
C) final static public void main (String args[ ])
D) All are Correct

7. A top level class may have which one of the following access modifiers?
a) package
b) private
C) protected
d) public

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 28 of Resources Pvt. Ltd.
Programming in Java
8. A subclass is also called as
a) inner class
b) nested class
c) derived class
d) hidden class
9. Which of the following is not a wrapper class?
a) Vector
b) character
c) Boolean
d) Integer
10. 7 Which of the following method is used to initialize the instance variable of a class

a) class
b) public
C) Constructor
d) Destructor

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 29 of Resources Pvt. Ltd.
Programming in Java
Example for static nested class

class Main {
private static void outerMethod() {
System.out.println("inside outerMethod");
}

// A static inner class


static class Inner {
public static void method() {
System.out.println("Static inner class");
}
}
public static void main(String[] args) {
System.out.println("inside inner class Method");
outerMethod();
Main.Inner.method();
}
}

SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 30 of Resources Pvt. Ltd.
JAVA
ARRAY
STRING
JAVA ARRAYS
What is an Array ?

• An array is a collection of similar type of data. It is a container that holds data (values) of a single
type. for example, you can create an array that can hold 300 values in int data type

• In java, arrays are a functional construct that allows you to store and access a large number of
values conveniently.
How to declare an Array ?

In java, here is how we can declare an array.

DataType[] arrayName;

DataType: it can be primitive data types like int , char , double , byte , etc. or Objects of java
arrayName: it is an identifier

Example,
double[] data;

Here, data is an array that can hold values of type double.


How many elements can array hold ?

We have to allocate memory for the array. The memory will define the number of elements that the
array can hold.

double data = new double[10];


Here, the size of the array is 10. This means it can hold 10 elements. The size of an array is also
known as the length of an array.

Note: Once the length of the array is defined, it cannot be changed in the program.
lets take another example:

int[] age;
age = new int[5];

Here, age is an array. It can hold 5 values of int type.

In java, we can declare and allocate memory of an array in one single statement.
for example,

int[] age = new int[5];


Java Array Index

in Java, each element in an array are associated with a number. The number is known as an array
index.

We can access elements of an array by using those indices.

For example,

int[] age = new int[10];


Java Array Index

Here, we have an array of length is 10. In the image, we can see that each element consists of number
(array index). The array indices always start from 0.

Now, we can use the index number to access elements of the array. For example, to access the first
element of the array is we can use age[0] , and the second element is accessed using age[1] and so on.
class Main
If we did not store any value to an {
array, the array will store some public static void main(String args[])
{
default value (0 for int type and int[] age = int[10]; //create an array with length 10
false for boolean type) by itself. //access each element of the array using the index
for example, System.out.println(age[0]);
System.out.println(age[1]);
System.out.println(age[2]);
System.out.println(age[3]);
System.out.println(age[4]);
System.out.println(age[5]);
System.out.println(age[6]);
System.out.println(age[7]);
System.out.println(age[8]);
System.out.println(age[9]);
}
}
Here, we are individually accessing the elements of the array. There is a better way to access
elements of the array using a loop (generally for-loop).

class Main
{
public static void main(String[] args)
{
// create an array of length 5
int[] age = new int[10];

// accessing elements using for loop


for (int i = 0; i < 10; ++i)
{
System.out.println(age[i]);
}
}
}
How to initialize arrays in Java?

In Java, we can initialize arrays during declaration or you can initialize later in the program as per
your requirement.

Initialize an Array During Declaration


Here’s how you can initialize an array during declaration.
int[] age = {12, 4, 5, 2, 5, 3, 9, 45, 1, 11}
Let’s write a simple program to print elements of this array.

class Main
{ Output:
public static void main(String[] args)
{ Element at index 0: 12
// create an array Element at index 1: 4
int[] age = {12, 4, 5, 2, 5, 3, 9, 45, 1, 11}; Element at index 2: 5
Element at index 3: 2
// access elements of tha arau
for (int i = 0; i < 10; ++i)
Element at index 4: 5
{ Element at index 5: 3
System.out.println("Element at index " + i +": " + age[i]); Element at index 6: 9
} Element at index 7: 45
} Element at index 8: 1
} Element at index 9: 11
How to access array elements?
class Main
{
public static void main(String[] args)
{
int[] age = new int[5];

// insert 14 to third element


age[2] = 14;

// insert 34 to first element


age[0] = 34;

for (int i = 0; i < 5; ++i)


{
System.out.println("Element at index " + i +": " + age[i]);
}
}
}
Example: Arrays
The program below computes sum and average of values stored in an array of type int.

class Main {
public static void main(String[] args) {
int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
int sum = 0;
Double average;

// for each loop is used to access elements


for (int number: numbers) {
sum += number;
}

int arrayLength = numbers.length;

// Change sum and arrayLength to double as average is in double


average = ((double)sum / (double)arrayLength);

System.out.println("Sum = " + sum);


System.out.println("Average = " + average);
}
}
In the above example, we have created an array of named numbers. We have used the for…each loop to
access each element of the array.

Inside the loop, we are calculating the sum of each element. Notice the line,

int arrayLength = number.length;

Here, we are using the length attribute of the array to calculate the size of the array. We then calculate the
average using:

average = ((double)sum / (double)arrayLength);

As you can see, we are converting the int value into double. This is called type casting in Java.
JAVA – MULTIDIMENSIONAL ARRAY
JAVA – MULTIDIMENSIONAL ARRAY

A multidimensional array is an array of arrays. Each element of a multidimensional array is an array


itself. For example,

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

Here, we have created a multidimensional array named a. It is a 2-dimensional array, that can hold a
maximum of 12 elements,
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts with 0 and not 1.
Let’s take another example of the multidimensional array. This time we will be creating a 3-
dimensional array.

For example,

String[][][] data = new String[3][4][2];

Here, data is a 3d array that can hold a maximum of 24 (3*4*2) elements of type String.
How to initialize a 2d array in Java?

Here is how we can initialize a 2-dimensional array in Java.

int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};

As we can see, each element of the multidimensional array is an array itself. And also, unlike C/C++,
each row of the multidimensional array in Java can be of different lengths.
How to initialize a 2d array in Java?
Example: 2-D Array
In this example, we are creating a multidimensional array named a. Since each component of a
multidimensional array is also an array (a[0], a[1] and a[2] are also arrays).

Here, we are using the length attribute to calculate the length of each row.
class Main{
public static void main(String[] args) {

// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
// calculate the length of each row
System.out.println("Length of row 1: " + a[0].length);
System.out.println("Length of row 2: " + a[1].length);
System.out.println("Length of row 3: " + a[2].length);
}
}
Example: Print all elements of 2D array using Loop
class Main
{
public static void main(String[] args)
{

int[][] a = { {1, -2, 3}, {-4, -5, 6, 9}, {7}, };

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


{
for(int j = 0; j < a[i].length; ++j)
{
System.out.println(a[i][j]);
}
}
}
}
We can also use the for…each loop to access elements of the multidimensional array.

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

// create a 2d array
int[][] a = {{1, -2, 3}, {-4, -5, 6, 9}, {7}, };

// first for...each loop access the individual array


// inside the 2d array
for (int[] innerArray: a)
{
// second for...each loop access each element inside the row
for(int data: innerArray)
{
System.out.println(data);
}
}
}
}
How to initialize a 3d array in Java?
Let’s see how we can use a 3d array in Java. We can initialize a 3d array similar to the 2d array. For example,

// test is a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};

Basically, a 3d array is an array of 2d arrays. The rows of a 3d array can also vary in length just like in a 2d array.
Example Program
class Main
{
public static void main(String[] args) // for..each loop to iterate through
{ elements of 3d array
// create a 3d array for (int[][] array2D: test)
int[][][] test = { {
{ for (int[] array1D: array2D)
{1, -2, 3}, {
{2, 3, 4} for(int item: array1D)
}, {
{ System.out.println(item);
{-4, -5, 6, 9}, }
{1}, }
{2, 3} }
} }
}; }
JAVA STRING
Java String
In Java, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters 'h', 'e',
'l', 'l', and 'o'.

Unlike other programming languages, strings in Java are not primitive types (like int, char, etc). Instead, all strings are
objects of a predefined class named String. For example,

// create a string
String type = "java programming";

Here, we have created a string named type. Here, we have initialized the string with "java programming". In Java, we
use double quotes to represent a string.

The string is an instance of the String class.


Java String Methods
Java String provides various methods that allow us to perform different string operations. Here are
some of the commonly used string methods.
Methods Description

concat() joins the two strings together

equals() compares the value of two strings

charAt() returns the character present in the specified location

getBytes() converts the string to an array of bytes

indexOf() returns the position of the specified character in the string

length() returns the size of the specified string


Java String Methods

replace() replaces the specified old character with the specified new character

substring() returns the substring of the string

split() breaks the string into an array of strings

toLowerCase() converts the string to lowercase

toUpperCase() converts the string to uppercase

valueOf() returns the string representation of the specified data


Example 1: Java find string's length

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

// create a string
String greet = "Hello! World";
System.out.println("The string is: " + greet);

//checks the string length


System.out.println("The length of the string: " + greet.length());
}
}

In the above example, we have created a string named greet. Here we have used the length() method to
get the size of the string.
Example 2: Java join two strings using concat()

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

// create string
String greet = "Hello! ";
System.out.println("First String: " + greet); In the above example, we have created 2
strings named greet and name.
String name = "World";
System.out.println("Second String: " + name); Here, we have used the concat() method
to join the strings. Hence, we get a new
// join two strings string named joinedString.
String joinedString = greet.concat(name);
System.out.println("Joined String: " + joinedString);
}
}
Example 3: Java join strings using + operator

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

// create string
String greet = "Hello! ";
System.out.println("First String: " + greet);

String name = "World";


System.out.println("Second String: " + name);

// join two strings


String joinedString = greet + name;
System.out.println("Joined String: " + joinedString);
}
}
Here, we have used the + operator to join the two strings.
Example 4: Java compare two strings
class Main {
public static void main(String[] args) {

// create strings
String first = "java programming";
String second = "java programming";
String third = "python programming";

// compare first and second strings


boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);

//compare first and third strings


boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}
}
Example 4: Java compare two strings

In the above example, we have used the equals() method to compare the value of two strings.

The method returns true if both strings are the same otherwise it returns false.

Note: We can also use the == operator and compareTo() method to make a comparison between 2
strings.
Example 5: Java get characters from a string
class Main {
public static void main(String[] args) {

// create string using the string literal


In the above example, we have used
String greet = "Hello! World"; the charAt() method to access the
System.out.println("The string is: " + greet); character from the specified position.

// returns the character at 3


System.out.println("The character at 3: " + greet.charAt(3));

// returns the character at 7


System.out.println("The character at 7: " + greet.charAt(7));
}
}
Example 6: Java Strings other methods
class Main {
public static void main(String[] args) {

// create string using the new keyword


String example = new String("Hello! World");

// returns the substring World


System.out.println("Using the subString(): " + example.substring(7));

// converts the string to lowercase


System.out.println("Using the toLowerCase(): " + example.toLowerCase());

// converts the string to uppercase


System.out.println("Using the toUpperCase(): " + example.toUpperCase());

// replaces the character '!' with 'o'


System.out.println("Using the replace(): " + example.replace('!', 'o'));
}
}
Example 6: Java Strings other methods

In the above example, we have created a string named example using the new keyword.

Here,

the substring() method returns the string World


the toLowerCase() method converts the string to the lower case
the toUpperCase() method converts the string to the upper case
the replace() method replaces the character '!' with 'o'.
Escape characters in strings
Strings in Java are represented by double-quotes. For example,

// create a string
String example = "This is a string";

Now if we want to include double-quotes in our string. For example,

// include double quote


String example = "This is the "String" class";

This will cause an error. It is because double-quotes are used to represent the string. Hence the compiler
will treat "This is the " as a string.
Escape characters in strings

To solve this issue, the escape character \ is used in Java. Now we can include double-quotes in the
string as:

// use the escape character


String example = "This is the \"String\" class.";

The escape character tells the compiler to escape the double quote and read the whole text.
Java Strings are Immutable

In Java, creating a string means creating an object of the String class. When we create a string, we
cannot change that string in Java. This is why strings are called immutable in Java.

To understand it more deeply, let's consider an example:

// create a string
String example = "Hello!";

Here, we have created a string object "Hello!". Once it is created, we cannot change it.
Java Strings are Immutable

Now suppose we want to change the string.

// adds another string to the string


example = example.concat(" World");

Here, we have tried to add a new string to the previous string.

Since strings are immutable, it should cause an error. But this works fine.
Now it looks like we are able to change the string. However, this is not true. Let's see what has
actually happened here.

We have a string "Hello!", referenced by the variable named example. Now while executing the
above code,

• the JVM takes the string "Hello!"


• appends the string " World" to it
• this creates a new string "Hello! World"
• the variable example now refers to the new string
• the previous string "Hello!" remains unchanged

Note: Every time a new string is created and it is referenced by a variable.


Creating strings using the new keyword

So far we have created strings like primitive types in Java. However, since strings in Java are objects, we
can create using the new keyword as well. For example,

// create a string using the new keyword


String name = new String("java string");

In the above example, we have used the new keyword along with the constructor String() to create a
string.

The String class provides various other constructors to create strings. To learn about all those
constructors, visit Java String (official Java documentation).
Differences between Using String literals and new keyword
Now that we know how strings are created using string literals and the new keyword, let's see what is the
major difference between them.

In Java, the JVM maintains a string pool to store all of its strings inside the memory. The string pool helps
in reusing the strings.

While creating strings using string literals, the value of the string is directly provided. Hence, the
compiler first checks the string pool to see if the string already exists.

If the string already exists, the new string is not created. Instead, the new reference points to the
existing string.
If the string doesn't exist, the new string is created.
STRING IN JAVA

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introduction
• String is a group of characters. In java it can be implemented using three classes
1. String class
2. StringBuffer class
3. StringBuilder class
• All these classes implements CharSequence interface

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Class
• Normally string is sequence of characters, but in java it’s an object which represents the
group of characters.
• String is immutable here.
• Java String class is used to create the string object.
• Two ways to create string object.
1. String Literal
2. Using new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Literal
• E.g.;
String s = “SMART”;
• That is by using the double quotes.
• If the string already exist in pool, the JVM will return a reference to the pooled instance
otherwise it will allocate a new memory.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Using new Keyword
• E.g.;
String s = new String(“SMART”);
• Here we will use the keyword new
• Every time a new memory will be created for this string.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java String Example
public class StringExample{
public static void main(String args[]){
String s1=“SMART";//creating string by java string literal
char ch[]={‘I’,’n’,’d’,’i’,’a’};
String s2=new String(ch);//converting char array to string
String s3=new String(“java");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output

SMART
India
java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Class Methods Description
int length() returns string length
String substring(int beginIndex) returns substring for given begin index
boolean isEmpty() checks if string is empty
String concat(String str) concatenates the given strings
String toLowercase() returns a string in lower case
String toUppercase() returns a string in upper case
String trim() removes the spaces in the beginning and the end of
the string
static String valueOf(int value) converts the given type into a string
int indexOf(String substring) returns the specified substring index

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String UpperCase and LowerCase Example
String s="Smart";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s);//no change in original

Output

SMART
smart
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String trim() method example
String s=" Smart ";
System.out.println(s);
System.out.println(s.trim());

Output
Smart
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Length example
String s="Sachin";
System.out.println(s.length());

Output
6

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String ofValue() example
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);

Output
1010

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String replace() Example

String s1="Java is a programming language. Java is an Island.";


String replaceString=s1.replace("Java","Kava");
System.out.println(replaceString);

Output
Kava is a programming language. Kava is an Island.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String concat() example

public class Example{


public static void main(String args[]){
String s1="java string";
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
java string
java string is immutable so assign it explicitly

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String equalsIgnoreCase()
• It compares the two given strings baesd on the content of the string.
• If anyone character is not matched it will return false otherwise returns true.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example

public class EqualsIgnoreCaseExample{


public static void main(String args[]){
String s1=“Smart";
String s2=“Smart";
String s3=“SMART";
String s4="python";
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println(s1.equalsIgnoreCase(s4));
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
true
true
false

Explanation
1. true because content and case both are same
2. true because case is ignored
3. false because content is not same

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which of the following will create new memory always?
a) String literal
b) new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2.
Which of the following is memory efficient when a string is used?
a) Creating string using new keyword
b) Creating string using string literal

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) Creating string using string literal

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java StringBuffer class
• StringBuffer class is used to create mutable or modifiable strings.
• This is thread safe i.e., multiple threads cannot access it simultaneously and hence it is
ordered.

Constructors in StringBuffer Class


1. StringBuffer() :- creates an empty string buffer
2. StringBuffer(String str) :- creates a string buffer with the specified string
3. StringBuffer(int capacity):- creates empty string with the specified capacity as length.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description
append() concatenates the given argument with the string
insert() inserts the given string with this string in the specified position
replace() replaces the given string from the specified beginIndex and
endIndex
delete() deletes the string from the specified beginIndex to endIndex
reverse() reverses the given string
capacity() returns the current capacity of the buffer
ensureCapacity() ensures that the given capacity is the minimum to the current
capacity

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String append() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello ");
str.append("Java"); Output
System.out.println(str);
Hello Java
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer insert() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello ");
str.insert(1,"Java");
System.out.println(str);
} Output

} HJavaello

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer replace() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello");
str.replace(1,3,"Java");
System.out.println(str);
} Output

} HJavalo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer reverse() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello");
str.reverse();
System.out.println(str);
} Output

} olleH

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
la

MCQ1.
Which of the following can be used to make mutable strings?
a) String class
b) StringBuffer class
c) StringBuilder class
d) Both b and c

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
d) Both b and c

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2.
What is the default capacity of the buffer?
a) 12
b) 10
c) 16
d) 20

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
c) Default capacity of buffer is 16. If character increases from current capacity it will increase
by((old capacity*2)+2).

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ3.
What will be the increased capacity if the current capacity is 16?
a) 20
b) 36
c) 50
d) 34

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
d) 34
New capacity = (old capacity*2)+2

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder Class
• StringBuilder class is similar to StringBuffer class except that this is non-synchronized.
• This creates mutable string

Constructors in StringBuilder Class


1. StringBuilder() :- creates an empty string builder with initial capacity as 16.
2. StringBuilder(String str) :- creates a string builder with the specified string
3. StringBuilder(int capacity):- creates empty string builder with the specified capacity as
length.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description
append() concatenates the given argument with the string
insert() inserts the given string with this string in the specified position
replace() replaces the given string from the specified beginIndex and
endIndex
delete() deletes the string from the specified beginIndex to endIndex
reverse() reverses the given string
capacity() returns the current capacity of the builder
ensureCapacity() ensures that the given capacity is the minimum to the current
capacity

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder append() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello ");
str.append("Java");
System.out.println(str);
}
Output
}
Hello Java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder insert() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello ");
str.insert(1,"Java");
System.out.println(str);
Output
}
HJavaello
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder replace() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.replace(1,3,"Java");
System.out.println(str);
} Output
}
HJavalo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder delete() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.delete(1,3);
System.out.println(str);
} Output

} Hlo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder reverse() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.reverse();
System.out.println(str);//prints olleH
} Output

} olleH

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which of the following class is used for immutable string?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) String class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2
Which of the following can be used for mutable and ordered string?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
al

Answer
a) StringBuffer class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ3.
Which class can be used for non synchronized strings?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
c) StringBuilder class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringTokenizer Class
• It helps us to break a given string into tokens.
• It cannot differentiate numbers, identifiers etc.

Constructors in StringTokenizer
1. StringTokenizer(String str) :- creates StringTokenizer with specified string
2. StringTokenizer(String str, String delim) :- creates StringTokenizer with specified string
and delimeter
3. StringTokenizer(String str, String delim, boolean returnValue) :- creates StringTokenizer
with specified string, delimeter and returnValue

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description

String nextToken() returns the next token from the StringTokenizer object

String nextToken(String delim) returns the next token based on the delimeter

boolean hasMoreTokens() checks if there is more tokens available

boolean hasMoreElements() same as hasMoreTokens() method

Object nextElement() same as nextToken() but its return type is Object

int countTokens() returns the total number of tokens

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringTokenizer class Example

import java.util.StringTokenizer;
public class Tokenss{
public static void main(String args[]){
StringTokenizer str = new StringTokenizer(“I am working in Smart"," ");
while (str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
I
am
working
in
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which among the following class is used to split a string into tokens?
a) StringBuffer
b) StringTokenizer
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) StringTokenizer

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Predict the output

import java.util.*;
public class Tokenss {
public static void main(String[] args) {
StringTokenizer str = new StringTokenizer(“I,am,working,in,smart");
System.out.println("Next token is : " + str.nextToken(","));
} }

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output

Next token is : I

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thankyou

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
STRING IN JAVA

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introduction
• String is a group of characters. In java it can be implemented using three classes
1. String class
2. StringBuffer class
3. StringBuilder class
• All these classes implements CharSequence interface

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Class
• Normally string is sequence of characters, but in java it’s an object which represents the
group of characters.
• String is immutable here.
• Java String class is used to create the string object.
• Two ways to create string object.
1. String Literal
2. Using new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Literal
• E.g.;
String s = “SMART”;
• That is by using the double quotes.
• If the string already exist in pool, the JVM will return a reference to the pooled instance
otherwise it will allocate a new memory.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Using new Keyword
• E.g.;
String s = new String(“SMART”);
• Here we will use the keyword new
• Every time a new memory will be created for this string.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java String Example
public class StringExample{
public static void main(String args[]){
String s1=“SMART";//creating string by java string literal
char ch[]={‘I’,’n’,’d’,’i’,’a’};
String s2=new String(ch);//converting char array to string
String s3=new String(“java");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output

SMART
India
java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Class Methods Description
int length() returns string length
String substring(int beginIndex) returns substring for given begin index
boolean isEmpty() checks if string is empty
String concat(String str) concatenates the given strings
String toLowercase() returns a string in lower case
String toUppercase() returns a string in upper case
String trim() removes the spaces in the beginning and the end of
the string
static String valueOf(int value) converts the given type into a string
int indexOf(String substring) returns the specified substring index

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String UpperCase and LowerCase Example
String s="Smart";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s);//no change in original

Output

SMART
smart
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String trim() method example
String s=" Smart ";
System.out.println(s);
System.out.println(s.trim());

Output
Smart
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Length example
String s="Sachin";
System.out.println(s.length());

Output
6

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String ofValue() example
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);

Output
1010

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String replace() Example

String s1="Java is a programming language. Java is an Island.";


String replaceString=s1.replace("Java","Kava");
System.out.println(replaceString);

Output
Kava is a programming language. Kava is an Island.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String concat() example

public class Example{


public static void main(String args[]){
String s1="java string";
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
java string
java string is immutable so assign it explicitly

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String equalsIgnoreCase()
• It compares the two given strings baesd on the content of the string.
• If anyone character is not matched it will return false otherwise returns true.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example

public class EqualsIgnoreCaseExample{


public static void main(String args[]){
String s1=“Smart";
String s2=“Smart";
String s3=“SMART";
String s4="python";
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println(s1.equalsIgnoreCase(s4));
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
true
true
false

Explanation
1. true because content and case both are same
2. true because case is ignored
3. false because content is not same

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which of the following will create new memory always?
a) String literal
b) new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2.
Which of the following is memory efficient when a string is used?
a) Creating string using new keyword
b) Creating string using string literal

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) Creating string using string literal

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java StringBuffer class
• StringBuffer class is used to create mutable or modifiable strings.
• This is thread safe i.e., multiple threads cannot access it simultaneously and hence it is
ordered.

Constructors in StringBuffer Class


1. StringBuffer() :- creates an empty string buffer
2. StringBuffer(String str) :- creates a string buffer with the specified string
3. StringBuffer(int capacity):- creates empty string with the specified capacity as length.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description
append() concatenates the given argument with the string
insert() inserts the given string with this string in the specified position
replace() replaces the given string from the specified beginIndex and
endIndex
delete() deletes the string from the specified beginIndex to endIndex
reverse() reverses the given string
capacity() returns the current capacity of the buffer
ensureCapacity() ensures that the given capacity is the minimum to the current
capacity

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String append() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello ");
str.append("Java"); Output
System.out.println(str);
Hello Java
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer insert() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello ");
str.insert(1,"Java");
System.out.println(str);
} Output

} HJavaello

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer replace() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello");
str.replace(1,3,"Java");
System.out.println(str);
} Output

} HJavalo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer reverse() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello");
str.reverse();
System.out.println(str);
} Output

} olleH

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
la

MCQ1.
Which of the following can be used to make mutable strings?
a) String class
b) StringBuffer class
c) StringBuilder class
d) Both b and c

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
d) Both b and c

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2.
What is the default capacity of the buffer?
a) 12
b) 10
c) 16
d) 20

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
c) Default capacity of buffer is 16. If character increases from current capacity it will increase
by((old capacity*2)+2).

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ3.
What will be the increased capacity if the current capacity is 16?
a) 20
b) 36
c) 50
d) 34

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
d) 34
New capacity = (old capacity*2)+2

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder Class
• StringBuilder class is similar to StringBuffer class except that this is non-synchronized.
• This creates mutable string

Constructors in StringBuilder Class


1. StringBuilder() :- creates an empty string builder with initial capacity as 16.
2. StringBuilder(String str) :- creates a string builder with the specified string
3. StringBuilder(int capacity):- creates empty string builder with the specified capacity as
length.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description
append() concatenates the given argument with the string
insert() inserts the given string with this string in the specified position
replace() replaces the given string from the specified beginIndex and
endIndex
delete() deletes the string from the specified beginIndex to endIndex
reverse() reverses the given string
capacity() returns the current capacity of the builder
ensureCapacity() ensures that the given capacity is the minimum to the current
capacity

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder append() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello ");
str.append("Java");
System.out.println(str);
}
Output
}
Hello Java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder insert() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello ");
str.insert(1,"Java");
System.out.println(str);
Output
}
HJavaello
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder replace() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.replace(1,3,"Java");
System.out.println(str);
} Output
}
HJavalo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder delete() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.delete(1,3);
System.out.println(str);
} Output

} Hlo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder reverse() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.reverse();
System.out.println(str);//prints olleH
} Output

} olleH

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which of the following class is used for immutable string?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) String class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2
Which of the following can be used for mutable and ordered string?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
al

Answer
a) StringBuffer class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ3.
Which class can be used for non synchronized strings?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
c) StringBuilder class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringTokenizer Class
• It helps us to break a given string into tokens.
• It cannot differentiate numbers, identifiers etc.

Constructors in StringTokenizer
1. StringTokenizer(String str) :- creates StringTokenizer with specified string
2. StringTokenizer(String str, String delim) :- creates StringTokenizer with specified string
and delimeter
3. StringTokenizer(String str, String delim, boolean returnValue) :- creates StringTokenizer
with specified string, delimeter and returnValue

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description

String nextToken() returns the next token from the StringTokenizer object

String nextToken(String delim) returns the next token based on the delimeter

boolean hasMoreTokens() checks if there is more tokens available

boolean hasMoreElements() same as hasMoreTokens() method

Object nextElement() same as nextToken() but its return type is Object

int countTokens() returns the total number of tokens

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringTokenizer class Example

import java.util.StringTokenizer;
public class Tokenss{
public static void main(String args[]){
StringTokenizer str = new StringTokenizer(“I am working in Smart"," ");
while (str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
I
am
working
in
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which among the following class is used to split a string into tokens?
a) StringBuffer
b) StringTokenizer
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) StringTokenizer

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Predict the output

import java.util.*;
public class Tokenss {
public static void main(String[] args) {
StringTokenizer str = new StringTokenizer(“I,am,working,in,smart");
System.out.println("Next token is : " + str.nextToken(","));
} }

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output

Next token is : I

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thankyou

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
STRING IN JAVA

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introduction
• String is a group of characters. In java it can be implemented using three classes
1. String class
2. StringBuffer class
3. StringBuilder class
• All these classes implements CharSequence interface

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Class
• Normally string is sequence of characters, but in java it’s an object which represents the
group of characters.
• String is immutable here.
• Java String class is used to create the string object.
• Two ways to create string object.
1. String Literal
2. Using new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Literal
• E.g.;
String s = “SMART”;
• That is by using the double quotes.
• If the string already exist in pool, the JVM will return a reference to the pooled instance
otherwise it will allocate a new memory.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Using new Keyword
• E.g.;
String s = new String(“SMART”);
• Here we will use the keyword new
• Every time a new memory will be created for this string.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java String Example
public class StringExample{
public static void main(String args[]){
String s1=“SMART";//creating string by java string literal
char ch[]={‘I’,’n’,’d’,’i’,’a’};
String s2=new String(ch);//converting char array to string
String s3=new String(“java");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output

SMART
India
java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Class Methods Description
int length() returns string length
String substring(int beginIndex) returns substring for given begin index
boolean isEmpty() checks if string is empty
String concat(String str) concatenates the given strings
String toLowercase() returns a string in lower case
String toUppercase() returns a string in upper case
String trim() removes the spaces in the beginning and the end of
the string
static String valueOf(int value) converts the given type into a string
int indexOf(String substring) returns the specified substring index

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String UpperCase and LowerCase Example
String s="Smart";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s);//no change in original

Output

SMART
smart
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String trim() method example
String s=" Smart ";
System.out.println(s);
System.out.println(s.trim());

Output
Smart
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Length example
String s="Sachin";
System.out.println(s.length());

Output
6

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String ofValue() example
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);

Output
1010

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String replace() Example

String s1="Java is a programming language. Java is an Island.";


String replaceString=s1.replace("Java","Kava");
System.out.println(replaceString);

Output
Kava is a programming language. Kava is an Island.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String concat() example

public class Example{


public static void main(String args[]){
String s1="java string";
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
java string
java string is immutable so assign it explicitly

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String equalsIgnoreCase()
• It compares the two given strings baesd on the content of the string.
• If anyone character is not matched it will return false otherwise returns true.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example

public class EqualsIgnoreCaseExample{


public static void main(String args[]){
String s1=“Smart";
String s2=“Smart";
String s3=“SMART";
String s4="python";
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println(s1.equalsIgnoreCase(s4));
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
true
true
false

Explanation
1. true because content and case both are same
2. true because case is ignored
3. false because content is not same

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which of the following will create new memory always?
a) String literal
b) new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2.
Which of the following is memory efficient when a string is used?
a) Creating string using new keyword
b) Creating string using string literal

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) Creating string using string literal

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java StringBuffer class
• StringBuffer class is used to create mutable or modifiable strings.
• This is thread safe i.e., multiple threads cannot access it simultaneously and hence it is
ordered.

Constructors in StringBuffer Class


1. StringBuffer() :- creates an empty string buffer
2. StringBuffer(String str) :- creates a string buffer with the specified string
3. StringBuffer(int capacity):- creates empty string with the specified capacity as length.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description
append() concatenates the given argument with the string
insert() inserts the given string with this string in the specified position
replace() replaces the given string from the specified beginIndex and
endIndex
delete() deletes the string from the specified beginIndex to endIndex
reverse() reverses the given string
capacity() returns the current capacity of the buffer
ensureCapacity() ensures that the given capacity is the minimum to the current
capacity

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String append() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello ");
str.append("Java"); Output
System.out.println(str);
Hello Java
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer insert() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello ");
str.insert(1,"Java");
System.out.println(str);
} Output

} HJavaello

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer replace() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello");
str.replace(1,3,"Java");
System.out.println(str);
} Output

} HJavalo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer reverse() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello");
str.reverse();
System.out.println(str);
} Output

} olleH

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
la

MCQ1.
Which of the following can be used to make mutable strings?
a) String class
b) StringBuffer class
c) StringBuilder class
d) Both b and c

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
d) Both b and c

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2.
What is the default capacity of the buffer?
a) 12
b) 10
c) 16
d) 20

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
c) Default capacity of buffer is 16. If character increases from current capacity it will increase
by((old capacity*2)+2).

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ3.
What will be the increased capacity if the current capacity is 16?
a) 20
b) 36
c) 50
d) 34

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
d) 34
New capacity = (old capacity*2)+2

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder Class
• StringBuilder class is similar to StringBuffer class except that this is non-synchronized.
• This creates mutable string

Constructors in StringBuilder Class


1. StringBuilder() :- creates an empty string builder with initial capacity as 16.
2. StringBuilder(String str) :- creates a string builder with the specified string
3. StringBuilder(int capacity):- creates empty string builder with the specified capacity as
length.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description
append() concatenates the given argument with the string
insert() inserts the given string with this string in the specified position
replace() replaces the given string from the specified beginIndex and
endIndex
delete() deletes the string from the specified beginIndex to endIndex
reverse() reverses the given string
capacity() returns the current capacity of the builder
ensureCapacity() ensures that the given capacity is the minimum to the current
capacity

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder append() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello ");
str.append("Java");
System.out.println(str);
}
Output
}
Hello Java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder insert() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello ");
str.insert(1,"Java");
System.out.println(str);
Output
}
HJavaello
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder replace() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.replace(1,3,"Java");
System.out.println(str);
} Output
}
HJavalo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder delete() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.delete(1,3);
System.out.println(str);
} Output

} Hlo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder reverse() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.reverse();
System.out.println(str);//prints olleH
} Output

} olleH

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which of the following class is used for immutable string?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) String class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2
Which of the following can be used for mutable and ordered string?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
al

Answer
a) StringBuffer class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ3.
Which class can be used for non synchronized strings?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
c) StringBuilder class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringTokenizer Class
• It helps us to break a given string into tokens.
• It cannot differentiate numbers, identifiers etc.

Constructors in StringTokenizer
1. StringTokenizer(String str) :- creates StringTokenizer with specified string
2. StringTokenizer(String str, String delim) :- creates StringTokenizer with specified string
and delimeter
3. StringTokenizer(String str, String delim, boolean returnValue) :- creates StringTokenizer
with specified string, delimeter and returnValue

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description

String nextToken() returns the next token from the StringTokenizer object

String nextToken(String delim) returns the next token based on the delimeter

boolean hasMoreTokens() checks if there is more tokens available

boolean hasMoreElements() same as hasMoreTokens() method

Object nextElement() same as nextToken() but its return type is Object

int countTokens() returns the total number of tokens

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringTokenizer class Example

import java.util.StringTokenizer;
public class Tokenss{
public static void main(String args[]){
StringTokenizer str = new StringTokenizer(“I am working in Smart"," ");
while (str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
I
am
working
in
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which among the following class is used to split a string into tokens?
a) StringBuffer
b) StringTokenizer
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) StringTokenizer

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Predict the output

import java.util.*;
public class Tokenss {
public static void main(String[] args) {
StringTokenizer str = new StringTokenizer(“I,am,working,in,smart");
System.out.println("Next token is : " + str.nextToken(","));
} }

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output

Next token is : I

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thankyou

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
STRING IN JAVA

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introduction
• String is a group of characters. In java it can be implemented using three classes
1. String class
2. StringBuffer class
3. StringBuilder class
• All these classes implements CharSequence interface

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Class
• Normally string is sequence of characters, but in java it’s an object which represents the
group of characters.
• String is immutable here.
• Java String class is used to create the string object.
• Two ways to create string object.
1. String Literal
2. Using new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Literal
• E.g.;
String s = “SMART”;
• That is by using the double quotes.
• If the string already exist in pool, the JVM will return a reference to the pooled instance
otherwise it will allocate a new memory.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Using new Keyword
• E.g.;
String s = new String(“SMART”);
• Here we will use the keyword new
• Every time a new memory will be created for this string.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java String Example
public class StringExample{
public static void main(String args[]){
String s1=“SMART";//creating string by java string literal
char ch[]={‘I’,’n’,’d’,’i’,’a’};
String s2=new String(ch);//converting char array to string
String s3=new String(“java");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output

SMART
India
java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Class Methods Description
int length() returns string length
String substring(int beginIndex) returns substring for given begin index
boolean isEmpty() checks if string is empty
String concat(String str) concatenates the given strings
String toLowercase() returns a string in lower case
String toUppercase() returns a string in upper case
String trim() removes the spaces in the beginning and the end of
the string
static String valueOf(int value) converts the given type into a string
int indexOf(String substring) returns the specified substring index

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String UpperCase and LowerCase Example
String s="Smart";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s);//no change in original

Output

SMART
smart
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String trim() method example
String s=" Smart ";
System.out.println(s);
System.out.println(s.trim());

Output
Smart
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String Length example
String s="Sachin";
System.out.println(s.length());

Output
6

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String ofValue() example
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);

Output
1010

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String replace() Example

String s1="Java is a programming language. Java is an Island.";


String replaceString=s1.replace("Java","Kava");
System.out.println(replaceString);

Output
Kava is a programming language. Kava is an Island.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String concat() example

public class Example{


public static void main(String args[]){
String s1="java string";
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
java string
java string is immutable so assign it explicitly

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String equalsIgnoreCase()
• It compares the two given strings baesd on the content of the string.
• If anyone character is not matched it will return false otherwise returns true.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example

public class EqualsIgnoreCaseExample{


public static void main(String args[]){
String s1=“Smart";
String s2=“Smart";
String s3=“SMART";
String s4="python";
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println(s1.equalsIgnoreCase(s4));
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
true
true
false

Explanation
1. true because content and case both are same
2. true because case is ignored
3. false because content is not same

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which of the following will create new memory always?
a) String literal
b) new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) new keyword

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2.
Which of the following is memory efficient when a string is used?
a) Creating string using new keyword
b) Creating string using string literal

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) Creating string using string literal

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java StringBuffer class
• StringBuffer class is used to create mutable or modifiable strings.
• This is thread safe i.e., multiple threads cannot access it simultaneously and hence it is
ordered.

Constructors in StringBuffer Class


1. StringBuffer() :- creates an empty string buffer
2. StringBuffer(String str) :- creates a string buffer with the specified string
3. StringBuffer(int capacity):- creates empty string with the specified capacity as length.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description
append() concatenates the given argument with the string
insert() inserts the given string with this string in the specified position
replace() replaces the given string from the specified beginIndex and
endIndex
delete() deletes the string from the specified beginIndex to endIndex
reverse() reverses the given string
capacity() returns the current capacity of the buffer
ensureCapacity() ensures that the given capacity is the minimum to the current
capacity

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
String append() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello ");
str.append("Java"); Output
System.out.println(str);
Hello Java
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer insert() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello ");
str.insert(1,"Java");
System.out.println(str);
} Output

} HJavaello

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer replace() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello");
str.replace(1,3,"Java");
System.out.println(str);
} Output

} HJavalo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuffer reverse() Example

class StringBufferExample{
public static void main(String args[]){
StringBuffer str=new StringBuffer("Hello");
str.reverse();
System.out.println(str);
} Output

} olleH

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
la

MCQ1.
Which of the following can be used to make mutable strings?
a) String class
b) StringBuffer class
c) StringBuilder class
d) Both b and c

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
d) Both b and c

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2.
What is the default capacity of the buffer?
a) 12
b) 10
c) 16
d) 20

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
c) Default capacity of buffer is 16. If character increases from current capacity it will increase
by((old capacity*2)+2).

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ3.
What will be the increased capacity if the current capacity is 16?
a) 20
b) 36
c) 50
d) 34

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
d) 34
New capacity = (old capacity*2)+2

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder Class
• StringBuilder class is similar to StringBuffer class except that this is non-synchronized.
• This creates mutable string

Constructors in StringBuilder Class


1. StringBuilder() :- creates an empty string builder with initial capacity as 16.
2. StringBuilder(String str) :- creates a string builder with the specified string
3. StringBuilder(int capacity):- creates empty string builder with the specified capacity as
length.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description
append() concatenates the given argument with the string
insert() inserts the given string with this string in the specified position
replace() replaces the given string from the specified beginIndex and
endIndex
delete() deletes the string from the specified beginIndex to endIndex
reverse() reverses the given string
capacity() returns the current capacity of the builder
ensureCapacity() ensures that the given capacity is the minimum to the current
capacity

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder append() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello ");
str.append("Java");
System.out.println(str);
}
Output
}
Hello Java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder insert() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello ");
str.insert(1,"Java");
System.out.println(str);
Output
}
HJavaello
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder replace() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.replace(1,3,"Java");
System.out.println(str);
} Output
}
HJavalo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder delete() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.delete(1,3);
System.out.println(str);
} Output

} Hlo

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringBuilder reverse() Example

class StringBuilderExample{
public static void main(String args[]){
StringBuilder str=new StringBuilder("Hello");
str.reverse();
System.out.println(str);//prints olleH
} Output

} olleH

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which of the following class is used for immutable string?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) String class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ2
Which of the following can be used for mutable and ordered string?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
al

Answer
a) StringBuffer class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ3.
Which class can be used for non synchronized strings?
a) StringBuffer
b) String class
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
c) StringBuilder class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringTokenizer Class
• It helps us to break a given string into tokens.
• It cannot differentiate numbers, identifiers etc.

Constructors in StringTokenizer
1. StringTokenizer(String str) :- creates StringTokenizer with specified string
2. StringTokenizer(String str, String delim) :- creates StringTokenizer with specified string
and delimeter
3. StringTokenizer(String str, String delim, boolean returnValue) :- creates StringTokenizer
with specified string, delimeter and returnValue

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Methods Description

String nextToken() returns the next token from the StringTokenizer object

String nextToken(String delim) returns the next token based on the delimeter

boolean hasMoreTokens() checks if there is more tokens available

boolean hasMoreElements() same as hasMoreTokens() method

Object nextElement() same as nextToken() but its return type is Object

int countTokens() returns the total number of tokens

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
StringTokenizer class Example

import java.util.StringTokenizer;
public class Tokenss{
public static void main(String args[]){
StringTokenizer str = new StringTokenizer(“I am working in Smart"," ");
while (str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output
I
am
working
in
Smart

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ1.
Which among the following class is used to split a string into tokens?
a) StringBuffer
b) StringTokenizer
c) StringBuilder

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer
b) StringTokenizer

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Predict the output

import java.util.*;
public class Tokenss {
public static void main(String[] args) {
StringTokenizer str = new StringTokenizer(“I,am,working,in,smart");
System.out.println("Next token is : " + str.nextToken(","));
} }

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output

Next token is : I

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thankyou

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Regex

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Regex

The Java Regex or Regular Expression is an API to define a pattern


for searching or manipulating strings.

It is widely used to define the constraint on strings such as password


and email validation. After learning Java regex tutorial, you will be able
to test your regular expressions by the Java Regex Tester Tool.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Regular Expressions are provided under java.util.regex package
This consists of 3 classes and 1 interface.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
java.util.regex package

The Matcher and Pattern classes provide the facility of Java regular
expression. The java.util.regex package provides following classes and
interfaces for regular expressions.
• MatchResult interface
• Matcher class
• Pattern class
• PatternSyntaxException class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The java.util.regex package primarily consists of the following three
classes:
CLASS DESCRIPTION

util.regex.Pattern Used for defining patterns


Used for performing match
util.regex.Matcher operations on text using
patterns
Used for indicating syntax
PatternSyntaxException error in a regular
expression pattern

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Pattern Class

A Pattern object is a compiled representation of a regular


expression. The Pattern class provides no public constructors. To create
a pattern, you must first invoke one of its public
static compile() methods, which will then return a Pattern object.
These methods accept a regular expression as the first argument.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MODIFIER AND TYPE METHOD DESCRIPTION

It is used to compile the given regular


static Pattern compile(String regex)
expression into a pattern.

It is used to compile the given regular


static Pattern compile(String regex, int flags)
expression into a pattern with the given flags.

int flags() It is used to return this pattern’s match flags.

It is used to create a matcher that will match


Matcher matcher(CharSequence input)
the given input against this pattern.

It is used to compile the given regular


static boolean matches(String regex, CharSequence input) expression and attempts to match the given
input against

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
It is used to return the regular expression from
String pattern()
which this pattern was compiled.

It is used to return a literal pattern String for the


static String quote(String s)
specified String.

It is used to split the given input sequence around


String[] split(CharSequence input)
matches of this pattern.

split(CharSequence input, It is used to split the given input sequence around


String[]
int limit) matches of this pattern.

It is used to return the string representation of this


String toString()
pattern.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Note:
The . (dot) represents a single character.

Example:
import java.util.regex.*;
class RegexExample2{
public static void main(String args[]){
System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)
System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)
System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)
System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)
System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Compile by: javac RegexExample2.java
Run by: java RegexExample2
true
false
false
false
true

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Matcher class

It implements the MatchResult interface. It is a regex engine which is


used to perform match operations on a character sequence.

No. Method Description

1 boolean matches() test whether the regular expression matches the


pattern.
2 boolean find() finds the next expression that matches the
pattern.
3 boolean find(int start) finds the next expression that matches the pattern
from the given start number.

4 String group() returns the matched subsequence.

5 int start() returns the starting index of the matched


subsequence.
6 int end() returns the ending index of the matched
subsequence.
7 int groupCount() returns the total number of the matched
subsequence.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Replacement Methods

Replacement methods are useful methods for replacing text in an input


string
Sr.No. Method & Description

1 public Matcher appendReplacement(StringBuffer sb, String replacement)


Implements a non-terminal append-and-replace step.

2 public StringBuffer appendTail(StringBuffer sb)


Implements a terminal append-and-replace step.

3 public String replaceAll(String replacement)


Replaces every subsequence of the input sequence that matches the pattern with the given replacement
string.

4 public String replaceFirst(String replacement)


Replaces the first subsequence of the input sequence that matches the pattern with the given
replacement string.

5 public static String quoteReplacement(String s)


Returns a literal replacement String for the specified String. This method produces a String that will
work as a literal replacement s in the appendReplacement method of the Matcher class.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The start and end Methods

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

private static final String REGEX = "\\bcat\\b";


private static final String INPUT = "cat cat cat cattie cat";

public static void main( String args[] ) {


Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
int count = 0;

while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Match number 1
start(): 0
end(): 3
Match number 2
start(): 4
end(): 7
Match number 3
start(): 8
end(): 11
Match number 4
start(): 19
end(): 22

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The matches and lookingAt Methods

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

private static final String REGEX = "foo";


private static final String INPUT = "fooooooooooooooooo";
private static Pattern pattern;
private static Matcher matcher;

public static void main( String args[] ) {


pattern = Pattern.compile(REGEX);
matcher = pattern.matcher(INPUT);

System.out.println("Current REGEX is: "+REGEX);


System.out.println("Current INPUT is: "+INPUT);

System.out.println("lookingAt(): "+matcher.lookingAt());
System.out.println("matches(): "+matcher.matches());
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
lookingAt(): true
matches(): false

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The replaceFirst and replaceAll Methods

The replaceFirst and replaceAll methods replace the text that


matches a given regular expression. As their names indicate,
replaceFirst replaces the first occurrence, and replaceAll replaces all
occurrences.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

private static String REGEX = "dog";


private static String INPUT = "The dog says meow. " + "All dogs say meow.";
private static String REPLACE = "cat";

public static void main(String[] args) {


Pattern p = Pattern.compile(REGEX);

// get a matcher object


Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:

The cat says meow. All cats say meow.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The appendReplacement and appendTail Methods

The Matcher class also provides appendReplacement and


appendTail methods for text replacement

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

private static String REGEX = "a*b";


private static String INPUT = "aabfooaabfooabfoob";
private static String REPLACE = "-";
public static void main(String[] args) {

Pattern p = Pattern.compile(REGEX);

// get a matcher object


Matcher m = p.matcher(INPUT);
StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, REPLACE);
}
m.appendTail(sb);
System.out.println(sb.toString()); © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD.
Output:

-foo-foo-foo-

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java program to demonstrate working of split()
to split a text based on a delimiter pattern
// Java program to demonstrate working of splitting a text by a
// given pattern
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Demo
{
public static void main(String args[])
{
String text = "Java1in2Regex3";

// Specifies the string pattern which is to be searched


String delimiter = "\\d";
Pattern pattern = Pattern.compile(delimiter,
Pattern.CASE_INSENSITIVE);

// Used to perform case insensitive search of the string


String[] result = pattern.split(text);

for (String temp: result)


System.out.println(temp);
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OutPut:
Java
in
Regex

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
PatternSyntaxException − A PatternSyntaxException object is an
unchecked exception that indicates a syntax error in a regular
expression pattern.
MODIFIER AND TYPE METHOD DESCRIPTION

String getDescription() It is used to retrieve the description of the error.

int getIndex() It is used to retrieve the error index.

It is used to return a multi-line string containing the


description of the syntax error and its index, the
String getMessage()
erroneous regular-expression pattern, and a visual
indication of the error index within the pattern.

It is used to retrieve the erroneous regular-expression


String getPattern()
pattern.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

public static void main( String args[] ) {


// String to be scanned to find the pattern.
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";

// Create a Pattern object


Pattern r = Pattern.compile(pattern);

// Now create matcher object.


Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
}else {
System.out.println("NO MATCH");
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Regex Character classes

No. Character Class Description

1 [abc] a, b, or c (simple
class)
2 [^abc] Any character except
a, b, or c (negation)
3 [a-zA-Z] a through z or A
through Z, inclusive
(range)
4 [a-d[m-p]] a through d, or m
through p: [a-dm-p]
(union)
5 [a-z&&[def]] d, e, or f
(intersection)
6 [a-z&&[^bc]] a through z, except
for b and c: [ad-z]
(subtraction)
7 [a-z&&[^m-p]] a through z, and not
m through p: [a-lq-
z](subtraction)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Regular Expression Character classes Example

import java.util.regex.*;
class RegexExample3{
public static void main(String args[]){
System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m
or n)
System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m
or n)
System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and
a comes more than once)
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Compile by: javac RegexExample3.java
Run by: java RegexExample3
false
true
false

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Regex Quantifiers

The quantifiers specify the number of occurrences of a character.

Regex Description

X? X occurs once or not at all


X+ X occurs once or more times
X* X occurs zero or more times
X{n} X occurs n times only
X{n,} X occurs n or more times
X{y,z} X occurs at least y times but less
than z times

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
import java.util.regex.*;
class RegexExample4{
public static void main(String args[]){
System.out.println("? quantifier ....");
System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)
System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one time)
System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes more than one time)
System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than one time)
System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come one time)

System.out.println("+ quantifier ....");


System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more times)
System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one time)
System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes more than once)
System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matching pattern)

System.out.println("* quantifier ....");


System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may come zero or more times)

}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Compile by: javac RegexExample4.java
Run by: java RegexExample4
? quantifier ....
true
false
false
false
false
+ quantifier ....
true
true
true
false
* quantifier ....
true

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Regex Metacharacters

The regular expression metacharacters work as shortcodes.


Regex Description

. Any character (may or may not match


terminator)
\d Any digits, short of [0-9]
\D Any non-digit, short for [^0-9]
\s Any whitespace character, short for
[\t\n\x0B\f\r]
\S Any non-whitespace character, short for [^\s]

\w Any word character, short for [a-zA-Z_0-9]

\W Any non-word character, short for [^\w]

\b A word boundary
\B A non word boundary
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
import java.util.regex.*;
class RegexExample5{
public static void main(String args[]){
System.out.println("metacharacters d....");

System.out.println(Pattern.matches("\\d", "abc"));
System.out.println(Pattern.matches("\\d", "1"));
System.out.println(Pattern.matches("\\d", "4443"));
System.out.println(Pattern.matches("\\d", "323abc"));

System.out.println("metacharacters D....");

System.out.println(Pattern.matches("\\D", "abc"));
System.out.println(Pattern.matches("\\D", "1"));
System.out.println(Pattern.matches("\\D", "4443"));
System.out.println(Pattern.matches("\\D", "323abc"));
System.out.println(Pattern.matches("\\D", "m"));
System.out.println("metacharacters D with quantifier....");
System.out.println(Pattern.matches("\\D*", "mak"));
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Compile by: javac RegexExample5.java
Run by: java RegexExample5
metacharacters d....
false
true
false
false
metacharacters D....
false
false
false
false
true
metacharacters D with quantifier....
true

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ’S

1. Which of the following is not a class of java.util.regex?


a) Pattern class
b) matcher class
c) PatternSyntaxException
d) Regex class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: d
Explanation: java.util.regex consists 3 classes. PatternSyntaxException
indicates syntax error in regex.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. What is the significance of Matcher class for regular expression in
java?
a) interpretes pattern in the string
b) Performs match in the string
c) interpreted both pattern and performs match operations in the string
d) None of the mentioned.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: c
Explanation: macther() method is invoked using matcher object which
interpretes pattern and performs match operations in the input string.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Object of which class is used to compile regular expression?
a) Pattern class
b) Matcher class
c) PatternSyntaxException
d) None of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: a
Explanation: object of Pattern class can represent compiled regular
expression.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Which capturing group can represent the entire expression?
a) group *
b) group 0
c) group * or group 0
d) None of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: b
Explanation: Group 0 is a special group which represents the entire
expression.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5. Which of the following matches nonword character using regular
expression in java?
a) \w
b) \W
c) \s
d) \S

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: b
Explanation: \W matches nonword characters. [0-9], [A-Z] and _
(underscore) are word characters. All other than these characters are
nonword characters.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. Which of the following matches end of the string using regular
expression in java?
a) \z
b) \\
c) \*
d) \Z

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: a
Explanation: \z is used to match end of the entire string in regular
expression in java.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7. What does public int end(int group) return?
a) offset from last character of the subsequent group
b) offset from first character of the subsequent group
c) offset from last character matched
d) offset from first character matched

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: a
Explanation: public int end(int group) returns offset from the last
character of the subsequent group.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. what does public String replaceAll(string replace) do?
a) Replace all characters that matches pattern with a replacement
string
b) Replace first subsequence that matches pattern with a replacement
string
c) Replace all other than first subsequence of that matches pattern with
a replacement string
d) Replace every subsequence of the input sequence that matches
pattern with a replacement string

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: d
Explanation: replaceAll method replaces every subsequence of the
sequence that matches pattern with a replacement string.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. What does public int start() return?
a) returns start index of the input string
b) returns start index of the current match
c) returns start index of the previous match
d) none of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: c
Explanation: public int start() returns index of the previous match in
the input string.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. What is the output of the following program?
import java.util.regex.*;

public class RegularEx {


public static void main(String... arg) {
Pattern pattern = Pattern.compile("M+", 5);
Matcher matcher = pattern.matcher("M Merit Match MM m mM");
while (matcher.find())
System.out.print(matcher.group() + " ");
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
D
C
B
E

A) M M M MM M
B) M M M m mM
C) M M M MM mM
D) PatternSyntax Error

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer:
A) M M M MM M

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Date and Time
Session 1
DATE

Date class in Java


The class Date represents a specific instant in time, with millisecond precision. The Date
class of java.util package implements Serializable, Cloneable and Comparable interface. It
provides constructors and methods to deal with date and time with java.

Constructors
Date() : Creates date object representing current date and time.
Date(long milliseconds) : Creates a date object for the given milliseconds since January 1,
1970, 00:00:00 GMT.
Date(int year, int month, int date)
Date(int year, int month, int date, int hrs, int min)
Date(int year, int month, int date, int hrs, int min, int sec)
Date(String s)
DATE

Date( )
This constructor initializes the object with the current date and time

Date(long millisec)

This constructor accepts an argument that equals the number of


milliseconds that have elapsed since midnight, January 1, 1970.
IMPORTANT METHODS IN DATE

boolean after(Date date)


Returns true if the invoking Date object contains a date that is
later than the one specified by date, otherwise, it returns
false.
boolean before(Date date)
Returns true if the invoking Date object contains a date that is
earlier than the one specified by date, otherwise, it returns
false.
Object clone( )
Duplicates the invoking Date object.
IMPORTANT METHODS IN DATE

int compareTo(Date date)


Compares the value of the invoking object with that of date. Returns 0 if
the values are equal.Returns a negative value of the invoking object is earlier
than date. Returns a positive value if the invoking object is later than date.

int compareTo(Object obj)


Operates identically to compareTo(Date) if obj is of class Date. Otherwise,
it throws a ClassCastException
boolean equals(Object date)
Returns true if the invoking Date object contains the same time and date
as the one specified by date, otherwise, it returns false.

long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.

int hashCode( )
Returns a hash code for the invoking object.
IMPORTANT METHODS IN DATE

void setTime(long time)


Sets the time and date as specified by time, which
represents an elapsed time in milliseconds from
midnight, January 1, 1970.

String toString( )
Converts the invoking Date object into a string and returns
the result.
Character Description Example
G Era designator AD

y Year in four digits 2001

M Month in year July or 07

d Day in month 1
0
h Hour in A.M./P.M. (1...,12) 1
2
H Hour In day (0 ..... 22
23)
m Minute In hour 30

s Second in minute 55

s Millisecond 23
4
E Day in week Tuesday

D Day in year 36
0
Java LocalDate Example

import java.time.LocalDate;
public class LocalDateExample1 {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalDate yesterday = date.minusDays(1);
LocalDate tomorrow = yesterday.plusDays(2);
System.out.println("Today date: "+date);
System.out.println("Yesterday date: "+yesterday);
System.out.println("Tommorow date: "+tomorrow);
}
}
Java LocalDate Example: isLeapYear()

import java.time.LocalDate;
public class LocalDateExample2 {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2017, 1, 13);
System.out.println(date1.isLeapYear());
LocalDate date2 = LocalDate.of(2016, 9, 23);
System.out.println(date2.isLeapYear());
}
}
LEAP YEAR OUTPUT

Output:
false
true
Java String to Date

We can convert String to Date in java using parse() method of


DateFormat and SimpleDateFormat classes.

SimpleDateFormat sdf=new SimpleDateFormat(“dd-mm-yyyy);


Date db=sdf.parse(dateString);
String dateStr= sdf.format(dateObj);
Date and Time
Session 2
Useful Date Patterns

PATTERN EXAMPLE
yyyy-MM-dd “2018-07-14”
dd-MMM-yyyy “14-Jul-2018”
dd/MM/yyyy “14/07/2018”
E, MMM dd yyyy “Sat, Jul 14 2018”
h:mm a “12:08 PM”

EEEE, MMM dd, yyyy HH:mm:ss a “Saturday, Jul 14, 2018 14:31:06 PM”

yyyy-MM-dd'T'HH:mm:ssZ “2018-07-14T14:31:30+0530”

hh 'o''clock' a, zzzz “12 o’clock PM, Pacific Daylight Time”

K:mm a, z “0:08 PM, PDT”


31/12/1998 Thu Dec 31 00:00:00 IST 1998

import java.text.SimpleDateFormat;
import java.util.Date;
public class Strdate
{
public static void main(String[] args)throws Exception
{
String sDate1="31/12/1998";
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
System.out.println(sDate1+"\t"+date1);
}
}
Output:
31/12/1998 Thu Dec 31 00:00:00 IST 1998
LOCAL TIME

import java.time.LocalTime;
public class LocalTimeExample3 {
public static void main(String[] args) {
LocalTime time1 = LocalTime.of(10,43,12);
System.out.println(time1);
LocalTime time2=time1.minusHours(2);
LocalTime time3=time2.minusMinutes(34);
System.out.println(time3);
}
}
LOCAL TIME OUTPUT

• Output:
10:43:12
08:09:12
Java LocalDateTime Example: plusDays()

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeExample5 {
public static void main(String[] args) {
LocalDateTime datetime1 = LocalDateTime.of(2017, 1, 14, 10, 34);
LocalDateTime datetime2 = datetime1.plusDays(120);
System.out.println("Before Formatting: " + datetime2);
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
String formatDateTime = datetime2.format(format);
System.out.println("After Formatting: " + formatDateTime );
}
}
Output:
Before Formatting: 2017-05-14T10:34
After Formatting: 14-05-2017 10:34
New Date-Time API in Java 8

New date-time API is introduced in Java 8 to overcome the following


drawbacks of old date-time API :
• Not thread safe : Unlike old java.util.Date which is not thread safe the new
date-time API is immutable and doesn’t have setter methods.
• Less operations : In old API there are only few date operations but the
new API provides us with many date operations.
Java 8 under the package java.time introduced a new date-time API, most
important classes among them are :
• Local : Simplified date-time API with no complexity of timezone handling.
• Zoned : Specialized date-time API to deal with various timezones.
• Period and Duration classes :
Period : It deals with date based amount of time.
Duration : It deals with time based amount of time.
PERIOD AND DURATION PROGRAM
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.time.Duration;
import java.time.Period;

public class sample {

public static void checkingPeriod()


{
LocalDate date1 = LocalDate.now();

LocalDate date2 = LocalDate.of(2014, Month.DECEMBER, 12);

Period gap = Period.between(date2, date1);

System.out.println("gap between dates "+ "is a period of "+gap);


}
PERIOD AND DURATION PROGRAM

public static void checkingDuraion() // Driver code


{
public static void main(String[] args)
LocalTime time1 = LocalTime.now(); {
System.out.println("the current time is " + time1); checkingPeriod();
Duration fiveHours = Duration.ofHours(5); checkingDuraion();
}
// adding five hours to the current
}
// time and storing it in time2
LocalTime time2 = time1.plus(fiveHours);

System.out.println("after adding five hours " +


"of duration " + time2);

Duration gap = Duration.between(time2, time1);


System.out.println("duraion gap between time1" +
" & time2 is " + gap);
}
PERIOD AND DURATION OUTPUT

Output:
gap between dates is a period of P3Y3M28D
the current time is 06:21:18.248
after adding five hours of duration 11:21:18.248
duraion gap between time1 & time2 is PT-5H
ChronoUnits Enum

• ChronoUnits Enum :
java.time.temporal.ChronoUnit enum is added in Java 8 to replace
integer values used in old API to represent day, month etc.
ChronoUnits Enum PROGRAM
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
// adding 1 week to the current date
public class Sample{ LocalDate nextWeek =
date.plus(1, ChronoUnit.WEEKS);
// Function to check ChronoUnit
public static void checkingChronoEnum() System.out.println("next week is " + nextWeek);
{
LocalDate date = LocalDate.now(); // adding 2 decades to the current date
System.out.println("current date is :" + LocalDate Decade =
date); date.plus(2, ChronoUnit.DECADES);
// adding 2 years to the current date System.out.println("20 years after today " +
LocalDate year = Decade);
date.plus(2, ChronoUnit.YEARS); }
System.out.println("next to next year is " + // Driver code
year); public static void main(String[] args) {
// adding 1 month to the current data checkingChronoEnum();
LocalDate nextMonth =
date.plus(1, ChronoUnit.MONTHS); }
}
System.out.println("the next month is " +
nextMonth);


ChronoUnits Enum OUTPUT

Output:
current date is :2018-04-09
next to next year is 2020-04-09
the next month is 2018-05-09
next week is 2018-04-16 20 years after today 2038-04-09
TemporalAdjuster

TemporalAdjuster : It is used to perform various date related operations.

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;

public class Sample


{

// Function to check date and time


// according to our requirement
public static void checkingAdjusters()
{
LocalDate date = LocalDate.now();
System.out.println("the current date is "+
date);

// to get the first day of next month


LocalDate dayOfNextMonth =
date.with(TemporalAdjusters. firstDayOfNextMonth());
System.out.println("firstDayOfNextMonth : " + dayOfNextMonth );
TemporalAdjuster

// get the next saturday


LocalDate nextSaturday =
date.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
System.out.println("next satuday from now is "+ nextSaturday);

// first day of current month


LocalDate firstDay =
date.with(TemporalAdjusters. firstDayOfMonth());
System.out.println("firstDayOfMonth : " + firstDay);

// last day of current month


LocalDate lastDay = date.with(TemporalAdjusters. lastDayOfMonth());
System.out.println("lastDayOfMonth : " + lastDay);
}
// Driver code
public static void main(String[] args)
{
checkingAdjusters();
}
}
TemporalAdjuster OUTPUT

Output:
the current date is 2018-04-09
firstDayOfNextMonth : 2018-05-01
next satuday from now is 2018-04-14
firstDayOfMonth : 2018-04-01
lastDayOfMonth : 2018-04-30
Date and Time
Session 3
Location Based Currency Formatting in Java
java.util.Locale : This class is used to get the location information of the
end user which is currently using your application.

java.util.Currency : This class represents a currency. The class is


designed so that there’s never more than one Currency instance for any
given currency. Therefore, there’s no public constructor. You obtain a
Currency instance using the getInstance methods.

java.text.NumberFormat : NumberFormat helps you to format and parse


numbers for any locale. We will use it’s getCurrencyInstance() method to
get the currency number formatter.
Localizing Currency
To localize the currency, you need to use various currency formats.
To determine the currency format according to the locale, you can
use the java.text.NumberFormat class.
To display the currency in German, the following code is used:
import java.text.*;
import java.util.*;
public class CurrencyDemo
{
public static void main(String args[])
{
NumberFormat nft = NumberFormat.getCurrencyInstance(new
Locale("de","DE"));
String formatted = nft.format(1000000);
System.out.println(formatted);
}
}
Localizing Text
To localize text, you need to use the resource bundles.
A resource bundle is a property file that contains the locale specific
data.
To work with data stored in a resource bundle, you need to use the
ResourceBundle class.
ResourceBundle class is a class that encapsulates a set of
resources.
To access a particular resource, you need to obtain a reference of
the ResourceBundle class and call its getObject() method.
To have a locale-specific object, a program needs to load the
ResourceBundle object by using the getBundle method, as
shown in the following code snippet:
ResourceBundle myResourceBundle =
ResourceBundle.getBundle("MessagesBundle");
Localizing Text
In case you need to develop a Java application that displays the
message, Welcome, in German or Chinese, you need to create the
German and Chinese resource bundles.
You can create the German resource bundle file, such as
MessageBundle_de.properties, and add the following code
snippet inside the file to localize the message, Welcome, in
German:
message=willkommen
You can create the Chinese resource bundle file, such as
MessageBundle_zn.properties, and add the following code
snippet inside the file to localize the message, Welcome, in
Chinese:
message=歡迎
Localizing Text
The following code demonstrates how the text is localized:
import java.util.Locale;
import java.util.ResourceBundle;
public class TestLocale {
public static void main(String args[]){
Locale l1=new Locale("de","DE");
ResourceBundle rb1 =
ResourceBundle.getBundle("MessageBundle",l1);
System.out.println(rb1.getString("message"));
Locale l2=new Locale("zn","ZN");
ResourceBundle rb2 =
ResourceBundle.getBundle("MessageBundle",l2);
System.out.println(rb2.getString("message"));
}

}
MULTIPLE CHOICE QUESTIONS
Which one of the following statements denotes the correct way to
create an instance of the Locale class?
Locale l=new Locale(“de”, “DE”);
Locale l=new Locale(“DE”, “de”);
Locale l=new Locale(‘de’, ‘DE’);
Locale l=new Locale(‘DE’, ‘de’);
MULTIPLE CHOICE QUESTIONS
Solution:
Locale l=new Locale(“de”, “DE”);
Date and Time
Session 4
Interview Question
1. How to implement Joda time in java program?
2. Compare two different dates whether they are equal or not.
3. Write a program to emphasis the importance of time shamp.
4. Convert Local date to zoned date time.
MULTIPLE CHOICE QUESTIONS
1.
LocalDate babyDOB = LocalDate.of(2015, Month.FEBRUARY, 20);
LocalDate now = LocalDate.of(2016, Month.APRIL, 10);
System.out.println(Period.between(now, babyDOB).getYears());
//PERIOD_CALC
A. The code segment results in a compiler error in the line marked with the
comment PERIOD_CALC
B. The code segment throws a DateTimeException
C. The code segment prints: 1
D. The code segment prints: -1
Solution:

D: The code segment prints: - 1

Here are the arguments to the between() method in the Period class:

Period between(LocalDate startDateInclusive, LocalDate


endDateExclusive)

The first argument is the start and the second argument is the end, and
hence the call Period.between(now, babyDOB) results in -1 (not +1).
MULTIPLE CHOICE QUESTIONS

2. How to format date from one form to another?


a) SimpleDateFormat
b) DateFormat
c) SimpleFormat
d) DateConverter
Solution

Answer: a
Explanation: SimpleDateFormat can be used as

Date now = new Date();


SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-mm-dd'T'hh:MM:ss");
String nowStr = sdf.format(now);
System.out.println("Current Date: " + );
MULTIPLE CHOICE QUESTIONS
3. Which one of the following classes is best suited for storing
timestamp values of application events in a file?
A. java.time.ZoneId class
B. java.time.ZoneOffset class
C. java.time.Instant class
D. java.time.Duration class
E. java.time.Period class
Solution:

C . Instant class

The Instant class stores the number of seconds elapsed since the start of
the Unix epoch (1970-01-01T00:00:00Z). The Instant class is suitable for
storing a log of application events in a file as timestamp values.

The ZoneId and ZoneOffset classes are related to time zones and hence
are unrelated to storing timestamp values. The Duration class is for
time-based values in terms of quantity of time (such as seconds, minutes,
and hours). The Period class is for date-based values such as years,
months, and days.
MULTIPLE CHOICE QUESTIONS

4. How to convert Date object to String?


a) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
sdf.parse(new Date());
b) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
sdf.format(new Date());
c) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); new
Date().parse();
d) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); new
Date().format();
Solution

Answer: b
Explanation: SimpleDateFormat takes a string containing
pattern.sdf.format converts the Date object to String.
5. Given this code segment:
ZoneId zoneId = ZoneId.of("Asia/Singapore");
ZonedDateTime zonedDateTime =
ZonedDateTime.of(LocalDateTime.now(), zoneId);
System.out.println(zonedDateTime.getOffset());
assume that the time-offset value for the Asia/Singapore time zone from
UTC/Greenwich is
+08:00. Choose the correct option.
A. This code segment results in throwing DateTimeException
B. This code segment results in throwing UnsupportedTemporalTypeException
C. The code segment prints: Asia/Singapore
D. The code segment prints: +08:00
E. This code segment prints: +08:00 [Asia/Singapore]
Solution:

D. The code segment prints: + 08:00

Given a ZonedDateTime object, the getOffset() method returns a


ZoneOffset object that corresponds to the offset of the time zone from
UTC/Greenwich. Given that the time-offset value for the Asia/
Singapore zone from UTC/Greenwich is +08:00, the toString() method of
ZoneOffset prints the string “+08:00” to the console.
MULTIPLE CHOICE QUESTIONS

6. How to convert a String to a Date object?


a) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
sdf.parse(new Date());
b) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
sdf.format(new Date());
c) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); new
Date().parse();
d) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); new
Date().format();
Solution

Answer: a
Explanation: SimpleDateFormat takes a string containing pattern.
sdf.parse converts the String to Date object.
MULTIPLE CHOICE QUESTIONS

7.
DateTieFormatter dateFormat = DateTimeFormatter.ISO_DATE; // DEF
LocalDate dateOfBirth = LocalDate.of(2015, Month.FEBRUARY, 31);
System.out.println(dateFormat.format(dateOfBirth)); // USE
A. The program gives a compiler error in the line marked with the comment DEF
B. The program gives a compiler error in the line marked with the comment USE
C. The code segment prints: 2015-02-31
D. The code segment prints: 2015-02-03
E. This code segment throws java.time.DateTimeException with the message
"Invalid date 'FEBRUARY 31'"
Solution

E. This code segment throws java.time.DateTimeException with the


message "Invalid date 'FEBRUARY 31'" .

The date value 31 passed in the call LocalDate.of(2015, 2, 3 1); is invalid


for the month February, and hence the of() method in the LocalDate class
throws DateTimeException.

One of the predefined values in DateTimeFormatter is ISO_DATE.


Hence, it does not result in a compiler error for the statement marked
with the comment DEF. The statement marked with the comment USE
compiles without errors because it is the correct way to use the format()
method in the DateTimeFormatter class.
MULTIPLE CHOICE QUESTIONS

8. What does LocalTime represent?


a) Date without time
b) Time without Date
c) Date and Time
d) Date and Time with timezone
Solution

Answer: b
Explanation: LocalTime of joda library represents time without date.
MULTIPLE CHOICE QUESTIONS

9. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE",


Locale.US);
System.out.println(formatter.format(LocalDateTime.now()));
Which of the following outputs matches the string pattern "EEEE" given
in this code segment?
A. F
B. Friday
C. Sept
D. September
Solution

B. Friday
E is the day name in the week; the pattern "EEEE" prints the name of
the day in its full format. “Fri” is a short form that would be printed by
the pattern “E", but "EEEE" prints the day of the week in full form: for
example, “Friday”. Because the locale is Locale.US, the result is printed
in English. The output “Sept” or “September” is impossible because E
refers to the name in the week, not in a month.
MULTIPLE CHOICE QUESTIONS

10. How to get difference between two dates?


a) long diffInMilli =
java.time.Duration.between(dateTime1,dateTime2).toMillis();
b) long diffInMilli =
java.time.difference(dateTime1, dateTime2).toMillis();
c) Date diffInMilli =
java.time.Duration.between(dateTime1,dateTime2).toMillis();
d) Time diffInMilli =
java.time.Duration.between(dateTime1, dateTime2).toMillis();
Solution

Answer: a
Explanation: Java 8 provides a method called between which provides
Duration between two times.
MULTIPLE CHOICE QUESTIONS

11. How is Date stored in database?


a) java.sql.Date
b) java.util.Date
c) java.sql.DateTime
d) java.util.DateTime
Solution

Answer: a
Explanation: java.sql.Date is the datatype of Date stored in database.
MULTIPLE CHOICE QUESTIONS

12. Is SimpleDateFormat thread safe?


a) True
b) False
Solution

Answer: b
Explanation: SimpleDateFormat is not thread safe. In the multithreaded
environment, we need to manage threads explicitly.
MULTIPLE CHOICE QUESTIONS

13. How to get UTC time?


a) Time.getUTC();
b) Date.getUTC();
c) Instant.now();
d) TimeZone.getUTC();
Solution

Answer: c
Explanation: In java 8, Instant.now() provides current time in UTC/GMT.
ARRAYS
- One Dimensional Arrays
- Two Dimensional Arrays
- Multi Dimensional Arrays
- Jagged Arrays

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
ARRAYS
• An array is a group of like-typed variables referred to by a common
name.
• It is a data structure where we store similar elements in a contiguous
memory location.
• Java array is an object and size is bounded.
• Size of an array must be specified by an int value.
• A specific element in an array is accessed by its index.
• If size of array is n ;index bounds from 0 to n-1.
• [0] is the first element.
• [1] is the second element, etc.
ONE-DIMENSIONAL ARRAYS
• A list of like-typed variables.
SYNTAX:
type array_name[ ]; // type [ ]array_name; // type[ ] array_name;
• base type determines the data type of each element of the array.
• array_name is set to null.
array_name=new type[size];
• new is a special operator that allocates memory of given size.
• Elements in the array are initialized to zero automatically by new operator.
type array_name[ ]=new type[size];
ONE-DIMENSIONAL ARRAYS
Examples:
int Array1[];
Array1 = new int[20];

• byte Arraybyte[];
• short Arrayshort[];
• boolean Arrayboolean[];
• long Arraylong[];
• float Arrayfloat[];
• double Arraydouble [];
• char Arraychar[];
• String Arraystr[];
• Class_Name Array_Object[]; //Array of objects
Declaration, Instantiation and Initialization of
Java Array
METHOD 1 METHOD 2
int a[]=new int[5]; int a[]={10,20,70,40,50};
//declaration and instantiation

//declaration, instantiation and


a[0]=10;//initialization
a[1]=20;
initialization
a[2]=70;
a[3]=40;
a[4]=50;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Array initialization using user input & accessing the elements using for
loop
class Ex1{
OUTPUT:
public static void main (String[] args) { 10
int[] arr; 20
arr = new int[5]; 30
Scanner in = new Scanner(System.in); 40
//getting user input 50
for (int i = 0; i <5; i++) Element at index 0:10
arr[i]=in.nextInt(); Element at index 1:20
// accessing the elements of the specified array
Element at index 2:30
for (int i = 0; i < arr.length; i++) //length method returns size of array
Element at index 3:40
System.out.println("Element at index " + i + " : "+ arr[i]);
}
Element at index 4:50
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Use of for each loop

for (int a:arr)


System.out.println(arr);
OUTPUT:
10
20
30
40
50

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
STRING ARRAYS

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for(String c:cars)
System.out.println(c);

OUTPUT:
Volvo
BMW
Ford
Mazda

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MULTI DIMENSIONAL ARRAYS

o Arrays of arrays.(ie) an array containing one or more arrays.


SYNTAX:
type[1st dimension][2nd dimension][]..[Nth
dimension] array_name = new type[size1][size2]….[sizeN];

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
TWO DIMENSIONAL ARRAYS:

• Data is stored in row and column based index.


SYNTAX:
• type[][] array_name;
• type [][]array_name;
• type array_name [][];
• type []array_name[];

 first[] indicates row size //compulsory


 Second[] indicates column size //optional

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Declaring and Initializing values
METHOD 1 METHOD 2
int a[][]=new int[3][4]; int a[][]={{5,15,25,35},{45,55,65,75},{85,95,105,115}};
a[0][0]=5;
a[0][1]=15;
a[0][2]=25;
a[0][3]=35;
a[1][0]=45;
a[1][1]=55;
a[1][2]=65;
a[1][3]=75;
a[2][0]=85;
a[2][1]=95;
a[2][2]=105;
a[2][3]=115;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Array initialization using user input & accessing elements
class TwoDArray { • OUTPUT:
public static void main(String args[]) {
int twoD[][]= new int[4][5]; ENTER THE ELEMENTS OF
ARRAY:
int i, j;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Scanner in = new Scanner(System.in); 16 17 18 19 20
System.out.println(“ENTER THE ELEMENTS OF ARRAY:”);
for(i=0; i<4; i++){
for(j=0; j<5; j++) { CONTENTS OF 2D ARRAY:
twoD[i][j]= in.nextInt(); 12345
}} 6 7 8 9 10
System.out.println(“CONTENTS OF 2D ARRAY:”); 11 12 13 14 15
for(i=0; i<4; i++) //i<twoD.length; 16 17 18 19 20
{
for(j=0; j<5; j++)//i<twoD[i].length;
{
System.out.print(twoD[i][j] + " ");
System.out.println();
}}
}}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3D Arrays

class threeD {
Example:
public static void main(String[] args)
{
int arr3[][][] = new int[3][4][5];
int[][][] arr =
{ { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
3 tables each with 4 rows and 5 columns
//2 tables each with 2 rows and 2 columns
for (int i = 0; i < 2; i++)
OUTPUT:
for (int j = 0; j < 2; j++)
12
for (int k = 0; k < 2; k++)
34
System.out.println(arr[i][j][k]);
56
}
78
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
JAGGED ARRAYS
- Ragged arrays
- Array of arrays such that member arrays can be of different sizes.
- 2-D arrays with variable number of columns in each row.

int myarray[][] = new int[4][];


myarray[0] = new int[1];
myarray[1] = new int[2];
myarray[2] = new int[3];
myarray[3] = new int[4];

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
EXAMPLE PROGRAM FOR JAGGED ARRAY
Class JagArray { OUTPUT:
public static void main(String args[]) {
int twoD[][] = new int[4][]; 0
twoD[0] = new int[1]; 12
twoD[1] = new int[2]; 345
twoD[2] = new int[3];
twoD[3] = new int[4]; 6789
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
ARRAYS AND METHODS
• Array passed to a method
 Syntax -
methodname(arrayname);
• Method returns array
 Syntax -
returntype[] methodname() {
return new arrayType[]{array elements};
}
or
returntype[] methodname() {
arrayType arrayname = { Array Elements } ;
return arrayname;
}
• Anonymous Array in Java
 Syntax -
methodname(new arrayType[]{array elements});

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
ARRAYS AND METHODS PROGRAM
public class TestArray{
OUTPUT
//creating method which returns an array
Passing an array – returned by
static int[] get(){ get()
return new int[]{10,30,50,90,60}; 10
} 30
public static void main(String args[]){ 50
//calling method which returns an array 90
int arr[]=get(); 60
System.out.println("Passing an array – returned by get()"); Passing an Anonymous array
PrintArray(arr); 10
System.out.println("Passing an Anonymous array"); 22
PrintArray(new int[]{10,22,44,66}); 44
} 66
static void PrintArray(int temp[])
{
//printing the values of an array
for(int i=0;i<temp.length;i++)
System.out.println(temp[i]);
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
CLASS OBJECTS FOR ARRAYS

public class Test


{  Every array has an
public static void main(String args[])
associated Class
{
object, shared with
int intArray[] = new int[3];
byte byteArray[] = new byte[3]; all other arrays with
short shortsArray[] = new short[3]; the same component
// array of Strings type.
String[] strArray = new String[3];
OUTPUT
System.out.println(intArray.getClass());
class [I
System.out.println(intArray.getClass().getSupercla
class java.lang.Object
ss());
class [B
System.out.println(byteArray.getClass());
class [S
System.out.println(shortsArray.getClass());
class [Ljava.lang.String;
System.out.println(strArray.getClass());
}
} SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
COPYING A ARRAY
SYNTAX :
public static void arraycopy ( Object src, int srcPos,Object dest, int destPos, int length)

//Java Program to copy a source array into a destination array in Java


class TestArrayCopyDemo OUTPUT
{ caffein
public static void main(String[] args)
{
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e','i', 'n', 'a', 't', 'e', ‘d' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(String.valueOf(copyTo));
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Note:

• Request for an index that is either negative, or greater than or equal to


the size of the array causes a run time error.
• Java Program throws a runtime exception “ArrayIndexOutOfBounds
Exception”.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
APPLICATIONS OF ARRAYS
• Leaderboards, Phone Contacts, Sudoku, Chess
• Playfair-cipher is an old encrypting algorithm that uses a 2D array of alphabets
as key to encrypt/decrypt text.
• 2D Arrays, generally called Matrices are mainly used in Image processing,
machine learning
• RGB image is a n*n*3 array
• It is used in Speech Processing where each speech signal is an array of Signal
Amplitudes
• Stacks are used for storing intermediate results in Embedded systems
• The filters that are used to remove noise in a recording are also arrays
• To makeSMART
webpage dynamic
TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQS:

1. Which of these best describes an array?


a) A data structure that shows a hierarchical behaviour
b) Container of objects of similar types
c) Arrays are immutable once initialised
d) Array is not a data structure

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. How do you initialize an array in Java?
a) int arr[3] = (1,2,3);
b) int arr(3) = {1,2,3};
c) int arr[3] = {1,2,3};
d) int arr(3) = (1,2,3);

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3.What is the output of the following piece of code?
public class array
{
public static void main(String args[])
{
int []arr = {1,2,3,4,5};
System.out.println(arr[5]);
}
}

a)4
b)5
c)ArrayIndexOutOfBoundsException
d) InavlidInputException

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4.Which of the following concepts make extensive use of arrays?
a) Binary trees
b) Scheduling of processes
c) Caching
d) Spatial locality

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5.Assuming int is of 4bytes, what is the size of int arr[15];?
a) 15
b) 19
c) 11
d) 60

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. Elements in an array are accessed _____________
a) randomly
b) sequentially
c) exponentially
d) logarithmically

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7. Which of the following is FALSE about arrays on Java?

a A java array is always an object


b Length of array can be changed after creation of array
c Arrays in Java are always allocated on hea

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8.Which one of the following is a valid statement?
a)char[] c = new char();
b)char[] c = new char[5];
c) char[] c = new char(4);
d)char[] c = new char[];

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. What is the result of compiling and running the following code?

public class Test{


public static void main(String[] args){
int[] a = new int[0];
System.out.print(a.length);
}
}
a. 0
b. Compilation error, arrays cannot be initialized to zero size.
c. Compilation error, it is a.length() not a.length
d. None of the above

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. What will be the output?
public class Test{
public static void main(String[] args){
int[] x = new int[3];
System.out.println("x[0] is " + x[0]);
}
}
a. The program has a compile error because the size of the array wasn't
specified when declaring the array.
b. The program has a runtime error because the array elements are not
initialized.
c. The program runs fine and displays x[0] is 0.
d. The program has a runtime error because the array element x[0] is not
defined.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. What is the output of the following code?
public class Test{
public static void main(String args[]){
double[] myList = {1, 5, 5, 5, 5, 1};
double max = myList[0];
int indexOfMax = 0;
for(int i = 1; i < myList.length; i++){
if(myList[i] > max){
max = myList[i];
indexOfMax = i;
}
}
System.out.println(indexOfMax);
}
}
a. 0
b. 1
c. 2
d. 3

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
12.What is output of the following code:
public class Test{
public static void main(String[] args){
int[] x = {120, 200, 016 };
for(int i = 0; i < x.length; i++)
System.out.print(x[i] + " ");
}
}
a. 120 200 16
b. 120 200 14
c. 120 200 016
d. 016 is a compile error. It should be written as 16.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
13. Determine output:
public class Test{
public static void main(String[] args){
int[] x = {1, 2, 3, 4};
int[] y = x;

x = new int[2];

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


System.out.print(y[i] + " ");
}
}
a. 1 2 3 4
b. 0 0 0 0
c. 1 2
d. 0 0 © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD.
14. Analyze the following code and choose the correct answer.
int[] arr = new int[5];
arr = new int[6];

a. The code has compile errors because the variable arr cannot be changed once it
is assigned.
b. The code has runtime errors because the variable arr cannot be changed once it
is assigned.
c. The code can compile and run fine. The second line assigns a new array to arr.
d. The code has compile errors because we cannot assign a different size array to
arr.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
15.What will be the output?
public class Test{
public static void main(String[] args){
int[] a = new int[4];
a[1] = 1;
a = new int[2];
System.out.println("a[1] is " + a[1]);
}
}
a. The program has a compile error because new int[2<sp< label="" style="outline:
none; box-sizing: border-box;"></sp<>
b. The program has a runtime error because a[1
c. a[1] is 0
d. a[1] is 1

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
16. When you pass an array to a method, the method receives ________ .
a. A copy of the array.
b. A copy of the first element.
c. The reference of the array.
d. The length of the array.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
17. What would be the result of attempting to compile and run the following code?
public class HelloWorld{
public static void main(String[] args){
double[] x = new double[]{1, 2, 3};
System.out.println("Value is " + x[1]);
}
}
a. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong
and it should be replaced by {1, 2, 3}.
b. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong
and it should be replaced by new double[3]{1, 2, 3};
c. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong
and it should be replaced by new double[]{1.0, 2.0, 3.0};
d. The program compiles and runs fine and the output

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
18.Which will legally declare, construct, and initialize an array?
a. int [] myList = {};
b. int [] myList = (5, 8, 2);
c. int myList [] [] = {4,9,7,0};
d. int myList [] = {4, 3, 7};

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
19. What will be the output of the program?
public class Test{
public static void main(String [] args){
String s1 = args[1];
String s2 = args[2];
String s3 = args[3];
String s4 = args[4];
System.out.print(" args[2] = " + s2);
}
}
and the command-line invocation is C:Java> java Test 1 2 3 4
a. args[2] = 2
b. args[2] = 3
c. args[2] = null
d. An exception is thrown at runtime.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
20. What is the value of a[1] after the following code is executed?

int[] a = {0, 2, 4, 1, 3};


for(int i = 0; i < a.length; i++)
a[i] = a[(a[i] + 3) % a.length];

a. 0
b. 1
c. 2
d. 3

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
21What will be the output of the following Java code?

class array_output
{
public static void main(String args[])
{
int array_variable [] = new int[10];
for (int i = 0; i < 10; ++i)
{
array_variable[i] = i;
System.out.print(array_variable[i] + " ");
i++;
}
}
}
a) 0 2 4 6 8
b) 1 3 5 7 9
c) 0 1 2 3 4 5 6 7 8 9
d) 1 2 3 4 5 6 7 8 9 10

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
22. What will be the output of the following Java code?

class multidimention_array
{
public static void main(String args[])
{
int arr[][] = new int[3][];
arr[0] = new int[1];
arr[1] = new int[2];
arr[2] = new int[3];
int sum = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < i + 1; ++j)
arr[i][j] = j + 1;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < i + 1; ++j)
sum + = arr[i][j];
System.out.print(sum);
}
}
a) 11
b) 10
c) 13
d) 14

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
23.What will be the output of the following Java code?

class evaluate
{
public static void main(String args[])
{
int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = 6;
n = arr[arr[n] / 2];
System.out.println(arr[n] / 2);
}
}
a) 3
b) 0
c) 6
d) 1 © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD.
24.What will be the output of the following Java code?

class array_output
{
public static void main(String args[])
{
int array_variable[][] = {{ 1, 2, 3}, { 4 , 5, 6}, { 7, 8, 9}};
int sum = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3 ; ++j)
sum = sum + array_variable[i][j];
System.out.print(sum / 5);
}
}
a) 8
b) 9
c) 10
d) 11

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
25. What will be the output of the following Java code?
class array_output
{
public static void main(String args[])
{
char array_variable [] = new char[10];
for (int i = 0; i < 10; ++i)
{
array_variable[i] = 'i';
System.out.print(array_variable[i] + "");
}
}
}
a) 1 2 3 4 5 6 7 8 9 10
b) 0 1 2 3 4 5 6 7 8 9 10
c) i j k l m n o p q r
d) i i i i i i i i i i © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD.
Answers: 13c
1b 14c
2c 15c
3c 16c
4d 17d
5d 18d
6a 19d
7b 20b
8b 21a
9a 22b
10c 23d
11b 24b
12b 25d
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
ARRAY PROGRAS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1. Sort a Numeric Array and a String Array

public class test {


System.out.println("Original numeric array :
public static void main(String[] args) {
"+Arrays.toString(my_array1));
Arrays.sort(my_array1);
int[] my_array1 = { System.out.println("Sorted numeric array :
1789, 2035, 1899, 1456, 2013, "+Arrays.toString(my_array1));
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456}; System.out.println("Original string array :
"+Arrays.toString(my_array2));
String[] my_array2 = { Arrays.sort(my_array2);
"Java",
System.out.println("Sorted string array :
"Python",
"PHP",
"+Arrays.toString(my_array2));
"C#",
"C Programming", }
"C++" }
};

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Sum of an array

public class test {


public static void main(String[] args) {

int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


int sum = 0;

for (int i : my_array)


sum += i;
System.out.println("The sum is " + sum);

}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Average of an array

Assignment To Do

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3.Average of an array
public class test {
public static void main(String[] args) {
int[] numbers = new int[]{20, 30, 25, 35, -16, 60, -100};
//calculate sum of all array elements
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];

//calculate average value


double average = sum / numbers.length;

System.out.println("Average value of the array elements is : " + average);


}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4.Test if an array contains a specific value or not
public class test {
public static boolean contains(int[] arr, int item) {
for (int n : arr) {
if (item == n) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2265, 1457, 2456};
System.out.println(contains(my_array1, 2013));
System.out.println(contains(my_array1, 2015));
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5.Find the index of an Array element

Assignment To Do

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5.Find the index of an Array element
public class test {
public static int findIndex (int[] my_array, int t) {
if (my_array == null) return -1;
int len = my_array.length;
int i = 0;
while (i < len) {
if (my_array[i] == t) return i;
else i=i+1;
}
return -1;
}
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
System.out.println("Index position of 25 is: " + findIndex(my_array, 25));
System.out.println("Index position of 77 is: " + findIndex(my_array, 77));
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6.Copy an array by iterating the array
public class test {
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
int[] new_array = new int[10];

System.out.println("Source Array : "+Arrays.toString(my_array));

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


new_array[i] = my_array[i];
}
System.out.println("New Array: "+Arrays.toString(new_array));
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7.Insert an element (specific position)into an array
public class test {

public static void main(String[] args) {


int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
// Insert an element in 3rd position of the array (index->2, value->5)
int Index_position = 2;
int newValue = 5;
System.out.println("Original Array : "+Arrays.toString(my_array));
for(int i=my_array.length-1; i > Index_position; i--){
my_array[i] = my_array[i-1];
}
my_array[Index_position] = newValue;
System.out.println("New Array: "+Arrays.toString(my_array));
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. Find the maximum and minimum value of an array

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


static int max; int[] my_array = {25, 14, 192, 15, 1, 56, 77, 18,
static int min; 29, 9};
max_min(my_array);
public static void max_min(int System.out.println(" Original Array:
my_array[]) { "+Arrays.toString(my_array));
max = my_array[0]; System.out.println(" Maximum value for the
min = my_array[0]; above array = " + max);
for (int i = 0; i < my_array.length; i++ ) System.out.println(" Minimum value for the
{ above array = " + min);
if(my_array[i]>max) { }
max = my_array[i]; }
}
if(my_array[i]<min) {
min = my_array[i];
}
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. Get the difference between the largest and smallest values in an array of
integers

Assignment To Do

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. Get the difference between the largest and
smallest values in an array of integers
public class test {
public static void main(String[] args)
{
int[] array_nums = {5, 7, 2, 4, 9};
System.out.println("Original Array: "+Arrays.toString(array_nums));
int max_val = array_nums[0];
int min = array_nums[0];
for(int i = 1; i < array_nums.length; i++)
{
if(array_nums[i] > max_val)
max_val = array_nums[i];
else if(array_nums[i] < min)
min = array_nums[i];
}
System.out.println("Difference between the largest and smallest values of the said array:
"+(max_val-min));
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. Reverse an array of integer values
public class test {
public static void main(String[] args){
int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456};
System.out.println("Original array : "+Arrays.toString(my_array1));
for(int i = 0; i < my_array1.length / 2; i++)
{
int temp = my_array1[i];
my_array1[i] = my_array1[my_array1.length - i - 1];
my_array1[my_array1.length - i - 1] = temp;
}
System.out.println("Reverse array : "+Arrays.toString(my_array1));
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. Find the common elements between two arrays of integers

Assignment To Do

Hint : Use two for loops (inner and outer) then compare.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. Find the common elements between two
arrays of integers
public class test {
public static void main(String[] args)
{
int[] array1 = {1, 2, 5, 5, 8, 9, 7, 10};
int[] array2 = {1, 0, 8, 15, 6, 4, 7, 0};
System.out.println("Array1 : "+Arrays.toString(array1));
System.out.println("Array2 : "+Arrays.toString(array2));
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++){
if(array1[i] == (array2[j])){
System.out.println("Common element is : "+(array1[i]));
}
}
}
}
} SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
12. Add two matrices of the same size
public static void main(String args[]) System.out.println("Input the elements of second
{ matrix");
int m, n, c, d; for ( c = 0 ; c < m ; c++ )
Scanner in = new for ( d = 0 ; d < n ; d++ )
Scanner(System.in); array2[c][d] = in.nextInt();
System.out.println("Input number
of rows of matrix"); for ( c = 0 ; c < m ; c++ )
m = in.nextInt(); for ( d = 0 ; d < n ; d++ )
System.out.println("Input number sum[c][d] = array1[c][d] + array2[c][d];
of columns of matrix");
n = in.nextInt(); System.out.println("Sum of the matrices:-");
int array1[][] = new int[m][n];
int array2[][] = new int[m][n]; for ( c = 0 ; c < m ; c++ )
int sum[][] = new int[m][n]; {
for ( d = 0 ; d < n ; d++ )
System.out.println("Input elements System.out.print(sum[c][d]+"\t");
of first matrix");
System.out.println();
for ( c = 0 ; c < m ; c++ ) }
for ( d = 0 ; d < n ; d++ ) }
array1[c][d] = in.nextInt();
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
13. Remove the duplicate elements of a given array
and return the new length of the array
public class test {
public static void main(String[] args) {
int nums[] = {20, 20, 30, 40, 50, 50, 50};
System.out.println("Original array length: "+nums.length);
System.out.print("Array elements are: ");
for (int i = 0; i < nums.length; i++)
{
System.out.print(nums[i]+" ");
}
System.out.println("\nThe new length of the array is: "+array_sort(nums))
}

public static int array_sort(int[] nums) {


int index = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[index-1])
nums[index++] = nums[i];
}
return index;
}
} SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Assignment
14. Write a Java program to find smallest and second smallest
elements of a given array

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
ARRAY PROGRAMS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1. Sort a Numeric Array and a String Array

public class test {


System.out.println("Original numeric array :
public static void main(String[] args) {
"+Arrays.toString(my_array1));
Arrays.sort(my_array1);
int[] my_array1 = { System.out.println("Sorted numeric array :
1789, 2035, 1899, 1456, 2013, "+Arrays.toString(my_array1));
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456}; System.out.println("Original string array :
"+Arrays.toString(my_array2));
String[] my_array2 = { Arrays.sort(my_array2);
"Java",
System.out.println("Sorted string array :
"Python",
"PHP",
"+Arrays.toString(my_array2));
"C#",
"C Programming", }
"C++" }
};

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Sum of an array

public class test {


public static void main(String[] args) {

int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


int sum = 0;

for (int i : my_array)


sum += i;
System.out.println("The sum is " + sum);

}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Average of an array

Assignment To Do

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3.Average of an array
public class test {
public static void main(String[] args) {
int[] numbers = new int[]{20, 30, 25, 35, -16, 60, -100};
//calculate sum of all array elements
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];

//calculate average value


double average = sum / numbers.length;

System.out.println("Average value of the array elements is : " + average);


}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4.Test if an array contains a specific value or not
public class test {
public static boolean contains(int[] arr, int item) {
for (int n : arr) {
if (item == n) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2265, 1457, 2456};
System.out.println(contains(my_array1, 2013));
System.out.println(contains(my_array1, 2015));
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5.Find the index of an Array element

Assignment To Do

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5.Find the index of an Array element
public class test {
public static int findIndex (int[] my_array, int t) {
if (my_array == null) return -1;
int len = my_array.length;
int i = 0;
while (i < len) {
if (my_array[i] == t) return i;
else i=i+1;
}
return -1;
}
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
System.out.println("Index position of 25 is: " + findIndex(my_array, 25));
System.out.println("Index position of 77 is: " + findIndex(my_array, 77));
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6.Copy an array by iterating the array
public class test {
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
int[] new_array = new int[10];

System.out.println("Source Array : "+Arrays.toString(my_array));

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


new_array[i] = my_array[i];
}
System.out.println("New Array: "+Arrays.toString(new_array));
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7.Insert an element (specific position)into an array
public class test {

public static void main(String[] args) {


int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
// Insert an element in 3rd position of the array (index->2, value->5)
int Index_position = 2;
int newValue = 5;
System.out.println("Original Array : "+Arrays.toString(my_array));
for(int i=my_array.length-1; i > Index_position; i--){
my_array[i] = my_array[i-1];
}
my_array[Index_position] = newValue;
System.out.println("New Array: "+Arrays.toString(my_array));
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. Find the maximum and minimum value of an array

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


static int max; int[] my_array = {25, 14, 192, 15, 1, 56, 77, 18,
static int min; 29, 9};
max_min(my_array);
public static void max_min(int System.out.println(" Original Array:
my_array[]) { "+Arrays.toString(my_array));
max = my_array[0]; System.out.println(" Maximum value for the
min = my_array[0]; above array = " + max);
for (int i = 0; i < my_array.length; i++ ) System.out.println(" Minimum value for the
{ above array = " + min);
if(my_array[i]>max) { }
max = my_array[i]; }
}
if(my_array[i]<min) {
min = my_array[i];
}
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. Get the difference between the largest and smallest values in an array of
integers

Assignment To Do

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. Get the difference between the largest and
smallest values in an array of integers
public class test {
public static void main(String[] args)
{
int[] array_nums = {5, 7, 2, 4, 9};
System.out.println("Original Array: "+Arrays.toString(array_nums));
int max_val = array_nums[0];
int min = array_nums[0];
for(int i = 1; i < array_nums.length; i++)
{
if(array_nums[i] > max_val)
max_val = array_nums[i];
else if(array_nums[i] < min)
min = array_nums[i];
}
System.out.println("Difference between the largest and smallest values of the said array:
"+(max_val-min));
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. Reverse an array of integer values
public class test {
public static void main(String[] args){
int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456};
System.out.println("Original array : "+Arrays.toString(my_array1));
for(int i = 0; i < my_array1.length / 2; i++)
{
int temp = my_array1[i];
my_array1[i] = my_array1[my_array1.length - i - 1];
my_array1[my_array1.length - i - 1] = temp;
}
System.out.println("Reverse array : "+Arrays.toString(my_array1));
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. Find the common elements between two arrays of integers

Assignment To Do

Hint : Use two for loops (inner and outer) then compare.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. Find the common elements between two
arrays of integers
public class test {
public static void main(String[] args)
{
int[] array1 = {1, 2, 5, 5, 8, 9, 7, 10};
int[] array2 = {1, 0, 8, 15, 6, 4, 7, 0};
System.out.println("Array1 : "+Arrays.toString(array1));
System.out.println("Array2 : "+Arrays.toString(array2));
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++){
if(array1[i] == (array2[j])){
System.out.println("Common element is : "+(array1[i]));
}
}
}
}
} SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
12. Add two matrices of the same size
public static void main(String args[]) System.out.println("Input the elements of second
{ matrix");
int m, n, c, d; for ( c = 0 ; c < m ; c++ )
Scanner in = new for ( d = 0 ; d < n ; d++ )
Scanner(System.in); array2[c][d] = in.nextInt();
System.out.println("Input number
of rows of matrix"); for ( c = 0 ; c < m ; c++ )
m = in.nextInt(); for ( d = 0 ; d < n ; d++ )
System.out.println("Input number sum[c][d] = array1[c][d] + array2[c][d];
of columns of matrix");
n = in.nextInt(); System.out.println("Sum of the matrices:-");
int array1[][] = new int[m][n];
int array2[][] = new int[m][n]; for ( c = 0 ; c < m ; c++ )
int sum[][] = new int[m][n]; {
for ( d = 0 ; d < n ; d++ )
System.out.println("Input elements System.out.print(sum[c][d]+"\t");
of first matrix");
System.out.println();
for ( c = 0 ; c < m ; c++ ) }
for ( d = 0 ; d < n ; d++ ) }
array1[c][d] = in.nextInt();
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
13. Remove the duplicate elements of a given array
and return the new length of the array
public class test {
public static void main(String[] args) {
int nums[] = {20, 20, 30, 40, 50, 50, 50};
System.out.println("Original array length: "+nums.length);
System.out.print("Array elements are: ");
for (int i = 0; i < nums.length; i++)
{
System.out.print(nums[i]+" ");
}
System.out.println("\nThe new length of the array is: "+array_sort(nums))
}

public static int array_sort(int[] nums) {


int index = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[index-1])
nums[index++] = nums[i];
}
return index;
}
} SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Assignment
14. Write a Java program to find smallest and second smallest
elements of a given array

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Module 1

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
What is Programming?
• Programming is the process of writing an algorithm into a sequence of computer instructions.
Or you can simply say it is the process of writing programs.
• The process of transforming the solution of a specific problem into computer language.
• Programming requires skill, logical thinking and lots of experience.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Who is a Programmer?
• Programmers are the person who writes programs in a specific computer programming
language.
• They are highly skilled, hard working, problem solvers.
• The world’s first programmer was Ada Lovelace. She was widely known for her work on
Charles Babbage’s Analytical Engine

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Classification of Programming Languages
• Different languages have different purposes. Some types are:

• Machine languages, that are interpreted directly in hardware


• Assembly languages, that are thin wrappers over a corresponding machine language
• High-level languages, that are anything machine-independent
• System languages, that are designed for writing low-level tasks, like memory and process
management
• Scripting languages, that are generally extremely high-level and powerful
• Domain-specific languages, that are used in highly special-purpose areas only
• Visual languages, that are non-text based
• Esoteric languages, that are not really intended to be used, but are very interesting, funny, or
educational in some way

• These types are not mutually exclusive: Perl is both high-level and scripting; C is considered both high-level
and system.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Assembler Vs Compiler Vs Interpreter
• Compiler :
Compilers are used to convert high level languages (like C, C++ ) into machine code .
– Example : gcc , Microsoft Visual Studio
• Assembers :
Assembler are used to convert assembly language code into machine code.
– Examples : List of assembler
• Interpreter :
An interpreter is a computer program which executes a statement directly (at runtime).
– Examples: python , LISP

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Programming paradigms
• There are many different approaches to computer programming. These are called programming paradigms.
• Different approaches develop solutions to problems using programs using different paradigms.

• Even though most of the programming languages come under


one paradigm type, certain languages show elements related to
different paradigms.
• There are a number of programming languages. There are
differences among different programming language types.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Imperative Programming
• Imperative programming is the style of programming in which there is a sequence of statements that
change the state of the program.

Example : • The state of the total variable changed from 0 in the beginning of the program,
var total = 0; to 6 before the print function.
var a = 1;
var b = 5; • Imperative programming says how to do something. An example - the process
total = a + b of baking a cake.
print total;
• The program says how to do something in the correct sequence it should be
done, therefore order of execution (the order in which each statement is
executed) is important

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Declarative Programming
• Declarative programming is a programming paradigm … that expresses the logic of a
computation without describing its control flow.
– Examples would be HTML, XML, CSS, SQL, Prolog, Haskell, F#and Lisp.
• Declarative code focuses on building logic of software without actually describing its flow.
You are saying what without adding how.
– For example with HTML you use <img src="./image.jpg" />
– To tell browser to display an image and you don’t care how it does that.
• Imperative: C, C++, Java
• Declarative: SQL, HTML
• (Can Be) Mix: JavaScript, C#, Python

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example of Imperative and equivalent in Declarative

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OBJECT ORIENTED PROGRAMMING - OOP
• Object Oriented Programming is a popular methodology of programming any application.
• Java, is an Object Oriented Programming language.
• It allows users create the objects that they want and then create methods to handle those objects.
• Manipulating these objects to get results is the goal of Object Oriented Programming
• Object Oriented programming is a programming paradigm that is associated with the concept of Class and
Objects
• The four principles of object-oriented programming are,
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OBJECT ORIENTED PROGRAMMING - OOP
• OOP is designed in such a way that one should focus on an object while programming and
not the procedure.
• An object can be anything that we see around us.
• Object oriented programming brings programming close to real life, as we are always dealing
with an object, performing operations on it, using it's methods and variables etc.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
WHY OOPS
1. OOP provides a clear modular structure for programs
2. OOP makes it easy to maintain and modify existing code
3. OOP provides a good framework for code libraries where supplied software components can be
easily adapted and modified by the programmer.
4. Code Reusability
5. It is suitable for real world problems and real world works
6. OOPs lets the coder to change the implementation of an object without affecting any other code.
(Encapsulation)
7. OOPs lets the coder to think about what should be exposed to the outside world and what should
be hidden. (Abstraction)
8. OOPs allows the coder to have many different functions, all with the same name, all doing the
same job, but on different data. (Polymorphism)
9. OOPs lets the coder to write a set of functions, then expand them in different direction without
changing or copying them in any way. (Inheritance)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - CLASS
• A class is a template or blueprint that is used to create objects.
• The class is a group of similar entities.
• A class consists of Data members and methods.
• The member functions determine the behavior of the class, i.e. provide a definition for supporting various
operations on data held in the form of an object.
• It is only an logical component and not the physical entity.
– For example, if you had a class called “Expensive Cars” it could have objects like Mercedes,
BMW, Toyota, etc. Its properties(data) can be price or speed of these cars. While the methods
may be performed with these cars are driving, reverse, braking etc.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - OBJECTS
• In real-world an entity that has state and its behavior is known as an object.
• In terms of object-oriented programming, software objects also have a state and behavior.

For Example:
• A Car is an object. It has states (name, color,
model) and its behavior (changing gear,
applying brakes).
• A Pen is an object. Its name is Parker; color is
silver etc. known as its state. It is used to
write, so writing is its behavior.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - OBJECTS
• An object can be defined as an instance of a class, and there can
be multiple instances of a class in a program.
• An Object contains both the data and the function, which
operates on the data.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - ENCAPSULATION

• Encapsulation is the technique used to implement abstraction in object-oriented


programming. Encapsulation is used for access restriction to class members and methods.
• Enclosing one or more details from outside world (Private) through access rights.
• Other objects don’t have direct access to this state. Instead, they can only call a list of public
functions — called methods
• The object manages its own state via methods — and no other class can touch it unless
explicitly allowed.
• If you want to communicate with the object, you should use the methods provided.
• But (by default), you can’t change the state

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - Encapsulation

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - Encapsulation
• The “state” of the cat is the private variables mood, hungry and energy. It also has a private
method meow(). It can call it whenever it wants, the other classes can’t tell the cat when to
meow.
• What they can do is defined in the public methods sleep(), play() and feed().
• Each of them modifies the internal state somehow and may invoke meow(). Thus, the binding
between the private state and public methods is made.
• This is encapsulation.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - ABSTRACTION
• Abstraction can be thought of as a natural extension of encapsulation
• Abstraction is the concept of hiding the internal details (implementation) and describing things in
simple terms.
• Revealing relevant/necessary information and hiding the unwanted information is abstraction.
• Object-oriented design, programs are often extremely large.
• And separate objects communicate with each other a lot. So maintaining a large codebase like this
for years — with changes along the way — is difficult.
• Abstraction is a concept aiming to ease this problem
EXAMPLE
• In a mobile phone, dialing a number would call some method internally which will concatenate the
numbers and displays it on screen but, we don’t know what is happening internally.
• When you tap on the call option, it is sending signals to other person’s mobile(whom you are trying
to call) but we are unaware of it’s implementation.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - ABSTRACTION
• You interact with your phone by using only a few buttons. But implementation details are hidden.
• Only a short set of actions are known.
• Implementation changes —
for example, a software
update — rarely affect the
abstraction you use.

Cell phones are complex. But using them is simple.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - POLYMORPHISM
• Polymorphism means “many shapes” in Greek.
• Polymorphism is the concept where an object behaves differently in different situations.
• Performing a job in different ways.(One to many)
• Polymorphism gives a way to use a class exactly like its parent so there’s no confusion with mixing types. But
each child class keeps its own methods as they are.
• For example, in English, the verb run has a different meaning if you use it with a laptop, a foot race,
and business. Here, we understand the meaning of run based on the other words used along with it.The same
also applied to Polymorphism.
EXAMPLE
• We click photographs and record videos using the camera in a mobile phone.
• Various brands have a plethora of camera modes in a mobile like: split camera/panaroma/slow-mo.
• The basic purpose is to click/record, so the functionality of camera is the same in every mobile, whereas the
modes enable you to use your camera in different ways.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - POLYMORPHISM

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - INHERITANCE
• Inheritance is the object oriented programming concept where an object is based on another
object
• Inheritance is the mechanism of code reuse.
• The object that is getting inherited is called superclass and the object that inherits the
superclass is called subclass.
Example:
• The basic purpose of using a mobile phone is communication.
• There are several brands in mobiles. So, the brands of a mobile are using this basic
functionality(communication) by extending the mobile class functionality and adding their
own new features to their respective brands.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
OOP - INHERITANCE

By Inheriting each class adds


only what is necessary for it
while reusing common logic
with the parent classes

A private teacher is a type of teacher. And any teacher is a type of Person.


SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
1. Which of the following best defines a class?
a) Parent of an object
b) Instance of an object
c) Blueprint of an object
d) Scope of an object

2. Which Feature of OOP illustrated the code reusability?


a) Polymorphism
b) Abstraction
c) Encapsulation
d) Inheritance

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept

3. Which language does not support all 4 types of inheritance?


a) C++
b) Java
c) Kotlin
d) Small Talk

4. Why Java is Partially OOP language?


a) It supports usual declaration of primitive data types
b) It doesn’t support all types of inheritance
c) It allows code to be written outside classes
d) It does not support pointers

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept

5. Which concept of OOP is false for C++?


a) Code can be written without using classes
b) Code must contain at least one class
c) A class must have member functions
d) At least one object should be declared in code

6. Which of the two features match each other?


a) Inheritance and Encapsulation
b) Encapsulation and Polymorphism
c) Encapsulation and Abstraction
d) Abstraction and Polymorphism

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
7. Which feature allows open recursion, among the following?
a) Use of this pointer
b) Use of pointers
c) Use of pass by value
d) Use of parameterized constructor

8. Class is pass by _______


a) Value
b) Reference
c) Value or Reference, depending on program
d) Copy

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
9. Size of a class is :
a) Sum of size of all the variables declared inside the class
b) Sum of size of all the variables along with inherited variables in the class
c) Size of largest size of variable
d) Classes doesn’t have any size

10. Which class can have member functions without their implementation?
a) Default class
b) String class
c) Template class
d) Abstract class

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
11. Class with main() function can be inherited (True/False)
a) True
b) False

12. Which of the following pairs are similar?


a) Class and object
b) Class and structure
c) Structure and object
d) Structure and functions

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
13. Instance of which type of class can’t be created?
a) Anonymous class
b) Nested class
c) Parent class
d) Abstract class

14. Which of the following pairs are similar?


a) Class and object
b) Class and structure
c) Structure and object
d) Structure and functions

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
15. If a function can perform more than 1 type of tasks, where the function name remains same,
which feature of OOP is used here?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction

16. If different properties and functions of a real world entity is grouped or embedded into a single
element, what is it called in OOP language?
a) Inheritance
b) Polymorphism
c) Abstraction
d) Encapsulation

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
17. How many basic features of OOP are required for a programming language to be purely
OOP?
a) 7
b) 6
c) 5
d) 4

18. The feature by which one object can interact with another object is:
a) Data transfer
b) Data Binding
c) Message Passing
d) Message reading

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
19. The feature by which one object can interact with another object is:
a) Data transfer
b) Data Binding
c) Message Passing
d) Message reading
20.Exception handling is feature of OOP. (True/False)
a) True
b) False

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MODULE 1 – Session 3

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Variables

• Variable is a piece of memory that can contain a data value.


• A variable thus has a data type
• Variables are typically used to store information
• This can be any kind of information ranging from texts, codes (e.g. country codes, currency
codes etc.) to numbers, temporary results of multi step calculations etc.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Types
• In Java there are four types of variables:

1. Non-static fields - A non-static field is a variable that belongs to an object. Objects keep their
internal state in non-static fields. Non-static fields are also called instance variables, because they
belong to instances (objects) of a class.

2. Static fields - A static field is a variable that belongs to a class. A static field has the same value for
all objects that access it. Static fields are also called class variables.

3. Local variables - A local variable is a variable declared inside a method. A local variable is only
accessible inside the method that declared it

4. Parameters - A parameter is a variable that is passed to a method when the method is called.
Parameters are also only accessible inside the method that declares them.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Data Type
• A data type, in programming, is a classification that specifies,
• Which type of value a variable has
• And what type of mathematical, relational or logical operations can be applied to it without causing
an error.
• A string, for example, is a data type that is used to classify text and an integer is a data type used to classify
whole numbers.
Data Type Used for Example
String Alphanumeric characters hello world, Alice, Bob123
Integer Whole numbers 7, 12, 999
Float (floating point) Number with a decimal point 3.15, 9.06, 00.13
Character Encoding text numerically 97 (in ASCII, 97 is a lower case 'a')
Boolean Representing logical values TRUE, FALSE

• The data type defines which operations can safely be performed to create, transform and use the variable in
another computation.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Strongly Typed And Weakly Typed
• Strongly Typed :
– Variable must be declared with a data type.
– A variable cannot start off life without knowing the range of values it can hold, and
once it is declared, the data type of the variable cannot change.
– A strongly typed language requires an explicit conversion (by using the cast
operator) between related types
– Java is a strongly typed programming language
• Weakly Typed :
– Variables are not associated to specific datatype
– Weakly typed languages place no restrictions on how data types can be mixed.
– Conversions between unrelated types are implicitly allowed.
– Example : Perl

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Data Types in Java
Data types specify the type of the values stored in variable. Two types of data types in java are
1. Primitive data types: The primitive data types include Boolean, char, byte, short, int, long,
float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java - Data Types and their Range
Data Type Default Value Default size Range
boolean false 1 bit true or false
char '\u0000' 2 byte 0 to 65535
byte 0 1 byte -128 to 127
short 0 2 byte -32,768 to 32,767
31 31
int 0 4 byte -2 to 2 -1
63 63
long 0L 8 byte -2 to 2 -1
float 0.0f 4 byte 1.4e-324 to 3.4e+038
double 0.0d 8 byte 4.9e-324 to 1.8e+308

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Primitive Data Types :
There are eight primitive datatypes supported by Java. Primitive datatypes
are predefined by the language and named by a keyword. Let us now look
into the eight primitive data types in detail.

Byte :
- Byte data type is an 8-bit signed two's complement integer
- Minimum value is -128 (-2^7)
- Maximum value is 127 (inclusive)(2^7 -1)
- Default value is 0
- Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an integer.
- Example: byte a = 100, byte b = -50

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
short

- Short data type is a 16-bit signed two's complement integer


- Minimum value is -32,768 (-2^15)
- Maximum value is 32,767 (inclusive) (2^15 -1)
- Short data type can also be used to save memory as byte data type.
- A short is 2 times smaller than an integer
- Default value is 0.
- Example: short s = 10000, short r = -20000

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Int

- Int data type is a 32-bit signed two's complement integer.


- Minimum value is - 2,147,483,648 (-2^31)
- Maximum value is 2,147,483,647(inclusive) (2^31 -1)
- Integer is generally used as the default data type for integral values
unless there is a concern about memory.
- The default value is 0
- Example: int a = 100000, int b = -200000

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
long

- Long data type is a 64-bit signed two's complement


integer
- Minimum value is -9,223,372,036,854,775,808(-2^63)
- Maximum value is 9,223,372,036,854,775,807
(inclusive)(2^63 -1)
- This type is used when a wider range than int is needed
- Default value is 0L
- Example: long a = 100000L, long b = -200000L

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Float

- Float data type is a single-precision 32-bit IEEE 754


floating point
- Float is mainly used to save memory in large arrays of
floating point numbers
- Default value is 0.0f
- Float data type is never used for precise values such as
currency
- Example: float f1 = 234.5f

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
double

- double data type is a double-precision 64-bit IEEE 754


floating point
- This data type is generally used as the default data type for
decimal values, generally the default choice
- Double data type should never be used for precise values
such as currency
- Default value is 0.0d
- Example: double d1 = 123.4

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Boolean

- boolean data type represents one bit of information


- There are only two possible values: true and false
- This data type is used for simple flags that track
true/false conditions
- Default value is false
- Example: boolean one = true

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Char

- char data type is a single 16-bit Unicode


character
- Minimum value is '\u0000' (or 0)
- Maximum value is '\uffff' (or 65,535 inclusive)
- Char data type is used to store any character
- Example: char letterA = 'A'

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Reference Datatypes :
Reference variables are created using defined constructors of the classes.
They are used to access objects. These variables are declared to be of a
specific type that cannot be changed. For example, Employee, Puppy, etc.

Class objects and various type of array variables come under reference
datatype.

Default value of any reference variable is null.

A reference variable can be used to refer any object of the declared type or
any compatible type.
Example: Animal animal = new Animal("giraffe");

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Literals :
A literal is a source code representation of a fixed value.
They are represented directly in the code without any computation.
Literals can be assigned to any primitive type variable.

For example −
byte a = 68;
char a = 'A';

byte, int, long, and short can be expressed in decimal(base 10),


hexadecimal(base 16) or octal(base 8) number systems as well.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Points to Remember:
• All numeric data types are signed (+/-).
• The size of data types remain the same on all platforms (standardized)
• Char data type in Java is 2 bytes because it uses UNICODE character set. By virtue of it, Java
supports internationalization.
• UNICODE is a character set which covers all known scripts and language in the world

Literals
• Literals are used to indicate simple values in your Java programs
• Different kinds of Literals in java are,
• numbers
• characters
• strings
• boolean values

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1. Numbers
Byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or
octal(base 8) number systems as well.
• byte a = 68;
• char a = 'A'
• int decimal = 100;
• int octal = 0144;
• int hexa = 0x64;
• int binary = 0b1111;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Characters and String
• String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes.
• Examples of string literals are −
"Hello World"
"two\nlines"
"\"This is in quotes\""
• Character literals are expressed by a single character surrounded by single quotes: ’a’, ’#’,
’3’, and so on. Characters are stored as 16-bit Unicode characters
• String and char types of literals can contain any Unicode characters.
• For example −
char a = '\u0001';
String a = "\u0001";

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Boolean literals
Boolean literals consist of the keywords true and false. These keywords can be used anywhere
you need a test or as the only possible values for Boolean variables.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Literals :
A literal is a source code representation of a fixed value.
They are represented directly in the code without any computation.
Literals can be assigned to any primitive type variable.

For example −
byte a = 68;
char a = 'A';

byte, int, long, and short can be expressed in decimal(base 10),


hexadecimal(base 16) or octal(base 8) number systems as well.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Prefix 0 is used to indicate octal, and prefix 0x indicates
hexadecimal when using these number systems for literals.

For example −
int decimal = 100;
int octal = 0144;
int hexa = 0x64;

String literals in Java are specified like they are in most other
languages by enclosing a sequence of characters between a pair of
double quotes. Examples of string literals are −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
"Hello World"
"two\nlines"
"\"This is in quotes\““

String and char types of literals can contain any Unicode characters.

For example −
char a = '\u0001';
String a = "\u0001";

Java language supports few special escape sequences for String and char
literals as well. They are −

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
. Notation Character represented

\n Newline (0x0a)

\r Carriage return (0x0d)

\f Formfeed (0x0c)

\b Backspace (0x08)

\s Space (0x20)

\t tab

\" Double quote

\' Single quote

\\ backslash

\ddd Octal character (ddd)

\uxxxx Hexadecimal UNICODE character


(xxxx)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
A variable provides us with named storage that our programs can
manipulate. Each variable in Java has a specific type, which
determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of
operations that can be applied to the variable.

You must declare all variables before they can be used. Following is
the basic form of a variable declaration −

data type variable [ = value][, variable [ = value] ...] ;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Here data type is one of Java's datatypes and variable is the name of the
variable. To declare more than one variable of the specified type, you can use
a comma-separated list.

Following are valid examples of variable declaration and initialization in


Java −

Example
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization byte
B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
This chapter will explain various variable types available in Java Language.
There are three kinds of variables in Java −
1. Local variables
2. Instance variables
3. Class/Static variables

Local Variables :
- Local variables are declared in methods, constructors, or blocks.
- Local variables are created when the method, constructor or block is
entered and the variable will be destroyed once it exits the method,
constructor, or block.
- Access modifiers cannot be used for local variables.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
- Local variables are visible only within the declared method,
constructor, or block.
- Local variables are implemented at stack level internally.
- There is no default value for local variables, so local variables
should be declared and an initial value should be assigned before the
first use.

Example :
Here, age is a local variable. This is defined inside pupAge() method
and its scope is limited to only this method.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}}
This will produce the following result −

Output :
Puppy age is: 7

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
Following example uses age without initializing it, so it would give an error at
the time of compilation.
public class Test {
public void pupAge() {
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
} public static void main(String args[]) {
Test test = new Test();
test.pupAge(); } }
This will produce the following error while compiling it −
Output :
Test.java:4:variable number might not have been initialized age = age + 7; ^ 1
error
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Instance Variables :
- Instance variables are declared in a class, but outside a method, constructor
or any block.
- When a space is allocated for an object in the heap, a slot for each instance
variable value is created.
- Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
- Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that must
be present throughout the class.
- Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
- The instance variables are visible for all methods, constructors and block in
the class. Normally, it is recommended to make these variables private
(access level). However, visibility for subclasses can be given for these
variables with the use of access modifiers.

- Instance variables have default values. For numbers, the default value is 0,
for Booleans it is false, and for object references it is null. Values can be
assigned during the declaration or within the constructor.

- Instance variables can be accessed directly by calling the variable name


inside the class. However, within static methods (when instance variables are
given accessibility), they should be called using the fully qualified
name. ObjectReference.VariableName.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
import java.io.*;
public class Employee { // this instance variable is visible for any
child class.
public String name; // salary variable is visible in Employee class
only.
private double salary; // The name variable is assigned in the
constructor.
public Employee (String empName) {
name = empName; } // The salary variable is assigned a value.
public void setSalary(double empSal) {
salary = empSal; }

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
// This method prints the employee details.
public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary); }
public static void main(String args[]) {
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}}
This will produce the following result −
Output :
name : Ransika salary :1000.0

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Class/Static Variables :
- Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
-
There would only be one copy of each class variable per class, regardless of
how many objects are created from it.

- Static variables are rarely used other than being declared as constants. -
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.

- Static variables are created when the program starts and destroyed when
the program stops.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Class/Static Variables :

- Static variables can be accessed by calling with the class


name ClassName.VariableName.

- When declaring class variables as public static final, then variable


names (constants) are all in upper case. If the static variables are not
public and final, the naming syntax is the same as instance and local
variables.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
import java.io.*;
public class Employee
{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[])
{
salary = 1000; System.out.println(DEPARTMENT + "average salary:"
+ salary);
}}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
This will produce the following result −

Output :
Development average salary:1000

Note − If the variables are accessed from an outside class, the


constant should be accessed as Employee.DEPARTMENT

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Example:
Add Two Numbers

class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}

Output:
20

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Example:
Widening

class Simple{
public static void main(String[] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output:
10
10.0

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Example:
Overflow

class Simple{
public static void main(String[] args){
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}
}
Output:
130
-126
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Example:
Narrowing (Typecasting)

class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}
}
Output:
10.5
10
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Variable Example:
Adding Lower Type

class Simple{
public static void main(String[] args){
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
System.out.println(c);
}
}
Output:
20

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Q) Why char uses 2 byte in java and what is \u0000 ?

It is because java uses Unicode system not ASCII code system.

The \u0000 is the lowest range of Unicode system.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Unicode System
• Unicode is a universal international standard character encoding that is capable
of representing most of the world's written languages.

• Why java uses Unicode System?


Before Unicode, there were many language standards: ASCII (American Standard
Code for Information Interchange) for the United States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for chinese, and so on.

lowest value:\u0000
highest value:\uFFFF

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQs
1. Which code fragment correctly assign a numeric literal?
A) byte b1 = b1011;
B) byte b2 = 1011b;
C) byte b3 = 0b1001;
D) byte b4 = 0xb001;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Given the fragment:
public class MathFun {
public static void main(String[] args) {
int number1 = 0b0111;
int number2 = 0111_000;
System.out.println("Number1: " + number1); OPTIONS :
A) Number1: 7
System.out.println("Number2: " + number1); Number2: 7
} B) Number1: 7
Number2: 111_000
} C) Number1: 0b0111
Number2: 0111000
What is the result? D) Compilation fails.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. class Main {
public static void main(String args[]) {
int t;
System.out.println(t);
}
} OPTIONS
(A) 0
(B) garbage value
(C) compiler error
(D) runtime error

4. Automatic type conversion in Java takes place when

OPTIONS :
A. Two type are compatible and size of destination type is shorter than source type.
B. Two type are compatible and size of destination type is equal of source type.
C. Two type are compatible and size of destination type is larger than source type.
D. All of the above

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5. What is the output of the following program?
class A{
public static void main(String args[]){
byte b;
int i = 258;
double d = 325.59;
b = (byte) i;
System.out.print(b);
i = (int) d;
System.out.print(i);
OPTIONS
b = (byte) d; A. 258 325 325
System.out.print(b); B. 258 326 326
} C. 2 325 69
} D. Error
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. What is the output of the following program?
public class Test{
public static void main(String [] a){
Scanner s= new Scanner(System.in);
int a=s.nextInt();
String str=s.nextLine(); INPUT :
5
System.out.println(a+” “+str);
Hello
}
OPTIONS :
} a) Hello
b) 5 Hello
c) 5
d) 5Hello

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7. What will be output of the following program code?
public class Test{
public static void main(String[] a){
short x = 10;
x = x*5;
System.out.print(x); OPTIONS :
A. 50
} B. 10
} C. Compilation Error
D. None of these

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. The following program:
public class Test{
static boolean isOK;
public static void main(String args[]){
System.out.print(isOK);
}
} OPTIONS :
A. Prints true
B. Prints false
C. Will not compile as boolean is not initialized
D. Will not compile as boolean can never be static

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. What will be the output of the program?
class Equals
{
public static void main(String [] args)
{
int x = 100;
double y = 100.1;
boolean b = (x = y); /* Line 7 */
OPTIONS :
System.out.println(b); A. true
} B. false
C. Compilation fails
} D. An exception is thrown at runtime

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. What is the output for the below code ?
1. public class Test{
2. public static void main(String[] args){
3. int i = 010;
4. int j = 07;
5. System.out.println(i); OPTIONS :
A. 8 7
6. System.out.println(j); B. 10 7
7. } C. Compilation fails with an error at line 3
D. Compilation fails with an error at line 5
8. } E. None of these

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. Select from among the following character escape code which is not
available in Java. OPTIONS :
A. t
B. r
C. a
12. .Determine output: D. \
public class Test{ E. “
public static void main(String... args){
int a=5 , b=6, c=7;
System.out.println("Value is "+ b + c);
System.out.println(a + b + c);
System.out.println("String " + (b+c));
} OPTIONS :
} A. Value is 67 18 String 13
B. Value is 13 18 String 13
C. Value is 13 18 String
D. Compilation fails

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
13. In Java, the word true is................
OPTIONS :
A. A Java keyword
B. A Boolean literal
C. Same as value 1
D. Same as value 0

14. What will be the output of the program?


class Equals
{
public static void main(String [] args)
{
int x = 100;
double y = 100.1;
boolean b = (x = y); /* Line 7 */ OPTIONS :
System.out.println(b); A. true
} B. false
} C. Compilation fails
D. An exception is thrown at runtime

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
15. Find the error:
public class Test{
public static void main(String [] args){
int a=55; \\line1
float b=45.59; \\line2
double c=67.4567; \\line3
System.out.println(a+“ ”+b+” “+c); \\line4
}
} OPTIONS :
a) line1
b) line2
c) line3
d) line 4

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
16. What is the valid data type for variable “a” to print “Hello World”?
switch(a)
{ OPTIONS:
System.out.println("Hello World"); a) int and float
b) byte and short
} c) char and long
d) byte and char

17. How many primitive data types are there in Java?


OPTIONS:
A. 6
B. 7
C. 8
D. 9

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
18. In Java byte, short, int and long all of these are
OPTIONS :
A. signed
B. unsigned
C. Both of the above
D. None of these

19. What is the range of data type byte in Java? OPTIONS :


A. -128 to 127
B. -32768 to 32767
C. -2147483648 to 2147483647
D. None of the mentioned

20. Which of these literals can be contained in a data type float variable?
OPTIONS :
A.1.7e-308
B. 3.4e-038
C. 1.7e+308
D. 3.4e-050

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Mcqs-Answers

1.C 11.C
2.A 12.A
3.C 13.B
4.C 14.C
5.C 15.B
6.C 16.D
7.C 17.C
8.B 18.A
9.C 19.A
10.A 20.B

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1. What is the range of data type short in Java?

A. -128 to 127
B. -32768 to 32767
C. -2147483648 to 2147483647
D. None of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. What is the range of data type byte in Java?

A. -128 to 127
B. -32768 to 32767
C. -2147483648 to 2147483647
D. None of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. An expression involving byte, int, and literal
numbers is promoted to which of these?

A. int
B. long
C. byte
D. float

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Which of these literals can be contained in a
data type float variable?

A. 1.7e-308
B. 3.4e-038
C. 1.7e+308
D. 3.4e-050

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
5. Which data type value is returned by all
transcendental math functions?

A. int
B. float
C. double
D. long

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
6. What is the numerical range of a char in
Java?

A. -128 to 127
B. 0 to 256
C. 0 to 32767
D. 0 to 65535

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7. Which of these coding types is used for data
type characters in Java?

A. ASCII
B. ISO-LATIN-1
C. UNICODE
D. None of the mentioned

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. Which of these values can a boolean variable
contain?

A. True & False


B. 0 & 1
C. Any integer value.
D. Both a & b

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
9. Which of these occupy first 0 to 127 in Unicode
character set used for characters in Java?

A. ASCII
B. ISO-LATIN-1
C. None of the mentioned
D. Both a & b

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
10. Which one is a valid declaration of a
boolean?

A. boolean b1 = 1;
B. boolean b2 = ‘false’;
C. boolean b3 = false;
D. boolean b4 = ‘true’

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
11. What is the output of this program?
class mainclass {
public static void main(String args[])
{
char a = 'A';
a++;
System.out.print((int)a);
}
}
A. 66
B. 67
C. 65
D. 64

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
12. What is the output of this program?
class mainclass {
public static void main(String args[])
{
boolean var1 = true;
boolean var2 = false;
if (var1)
System.out.println(var1);
else
System.out.println(var2);
}
}
A. 0
B. 1
C. true
D. false © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD.
13. Which of the following is smallest integer
data type ?

A. int
B. byte
C. short
D. long

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
14. Integer Data type does not include following
primitive data type ?

A. long
B. byte
C. short
D. double

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
15. Which of the following data types comes
under floating data types ?

A. int
B. double
C. long
D. byte

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
16. Range of Byte Data Type is
____________.

A. -128 to 128
B. -127 to 127
C. -127 to 128
D. -128 to 127

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
17. Which of the following data type(s) can store
64 bit Value.

A. boolean
B. int
C. float
D. long

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
18. Short data type has a minimum value of
____ .

A. -32,768
B. -32,767
C. 32768
D. 32767

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
19.Default value of variable having boolean data type
is ______.

A. True
B. False
C. Null
D. Garbage

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
20. What will be the output of the program?

class Main {
public static void main(String args[]) {
int t;
System.out.println(t);
}}

A. 0
B. garbage value
C. compiler error
D. runtime error

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
21. What will be the output of the program?

class Test {
public static void main(String[] args) {
for(int i = 0; 0; i++) {
System.out.println("Hello");
break;
}}}

A. Hello
B. Empty Output
C. Compiler error
D. Runtime error

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
22.What will be the output of the program?

class mainclass {
public static void main(String args[]) {
boolean var1 = true;
boolean var2 = false;
if (var1) System.out.println(var1);
else System.out.println(var2);
}}

A. 0
B. 1
C. true
D. false

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
23. Predict the output of the following program.

class Test {
public static void main(String[] args) {
Double object = new Double("2.4");
int a = object.intValue();
byte b = object.byteValue();
float d = object.floatValue();
double c = object.doubleValue();
System.out.println(a + b + c + d );
}}
A. 8
B. 8.8
C. 8.800000095367432
D. 8.0
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
24. What is the output of this program?

class average {
public static void main(String args[]) {
double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};
double result;
result = 0;
for (int i = 0; i<6; ++i)
result = result + num[i];
System.out.print(result/6);
}}
A. 16.34
B. 16.566666644
C. 16.46666666666667
D. 16.46666666666666
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
25. Which of the following are legal lines of Java code?
1. int w = (int)888.8;
2. byte x = (byte)100L;
3. long y = (byte)100;
4. byte z = (byte)100L;

A. 1 and 2
B. 2 and 3
C. 3 and 4
D. All statements are correct

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answers
1. B 14. D
2. A 15. B
3. A 16. D
4. B 17. D
5. C 18. A
6. D 19. B
7. C 20. C
8. A 21. C
9. D 22. C
10. C 23. C
11. A 24. C
12. C 25. D
13. B

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thank you

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Inheritance in Java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Inheritance:

Inheritance in Java is the concept of create new classes that are


built upon existing classes. When you inherit from an existing class,
you can reuse methods and fields of the parent class.

Inheritance represents the IS-A relationship which is also


known as a parent-child relationship.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Usage of Inheritance:

Method Overriding
Code Reusability.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Terms used in Inheritance:

Class: A class is a template or blueprint from which objects are


created.

Sub Class/Child Class: Subclass is a class which inherits the


other class. It is also called a derived class, extended class, or child
class.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a base class or a
parent class.

Reusability: Reusability is a mechanism which facilitates you


to reuse the fields and methods of the existing class when you create a
new class. You can use the same fields and methods already defined in
the previous class.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class
that derives from an existing class. The meaning of "extends" is to increase
the functionality.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Inheritance (Subclass and Superclass)
In Java, it is possible to inherit attributes and methods from
one class to another.
Two categories of inheritance concepts,

• subclass (child) - the class that inherits from another class


• superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Inheritance Example
Salary is the subclass and Employee is the superclass. The
relationship between the two classes is Salary IS-A Employee. It
means that Salary is a type of Employee.

In this example, Salary object can access the field of own class as well
as of Employee class i.e. code reusability.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Employee {

public void display() {


System.out.println("Employee Name : XYZ");
}

class Salary extends Employee {


public void salary() {
System.out.println("May month salary : 50000");
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Main {
public static void main(String[] args) {

Salary sal = new Salary();


sal.display();
sal.salary();

}
}
Output:
Employee Name : XYZ
May month salary : 50000

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Types of inheritance in java
Three types of inheritance in java,
single
multilevel
hierarchical.

In java programming, multiple and hybrid inheritance is supported


through interface only.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Single Inheritance:
When a class inherits another class, it is known as a single
inheritance

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Car
{
void model()
{
System.out.println("Car Model Name: XYZ");}
}
class Price extends Car
{
void display()
{
System.out.println("Price of the car: 700000");}
}
class Main{
public static void main(String args[]){
Price p = new Price();
p.model();
p.display();
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
Car Model Name: XYZ
Price of the car: 700000

In the above example, Price class inherits the Car class, so there
is the single inheritance.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel
inheritance.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Car
{
void model()
{
System.out.println("Car Model Name: XYZ");
}
}
class Price extends Car
{
void display()
{
System.out.println("Price of the car: 700000");
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Colour extends Price{
void colour()
{
System.out.println("Colour of the car: Black");
}
}
class Main{
public static void main(String args[]){
Colour C = new Colour();
C.model();
C.display();
C.colour();
}}
Output:
Car Model Name: XYZ
Price of the car: 700000
Colour of the car: Black

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Hierarchical Inheritance
When two or more classes inherits a single class, it is known
as hierarchical inheritance.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Car
{
void model()
{
System.out.println("Car Model Name: XYZ");
}
}
class Price extends Car
{
void display()
{
System.out.println("Price of the car: 700000");
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Colour extends Car{
void colour()
{
System.out.println("Colour of the car: Black");
}
}
class Main{
public static void main(String args[]){
Colour C = new Colour();
C.model();
//C.display();//Error
C.colour();
}}

Output:
Car Model Name: XYZ
Colour of the car: Black

In the example, Price and Colour classes inherits the Car class, so there is hierarchical
inheritance.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Multiple inheritance
 Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple


inheritance.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple


inheritance is not supported in java.
Multiple inheritance can cause ambiguity.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output:
Compile Time Error

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The final Keyword:

If you don't want other classes to inherit from a class, use


the final keyword.

If you try to access a final class, Java will generate an error:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
final class Vehicle {
...
}

class Car extends Vehicle {


...
}
Output:
Car.java:8: error: cannot inherit from final Vehicle
class Car extends Vehicle {
^
1 error)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ’s

1. Which of this keyword must be used to inherit a class?


a) super
b) this
c) extent
d) extends

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: d

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. A class member declared protected becomes a member of subclass of
which type?
a) public member
b) private member
c) protected member
d) static member

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: b
Explanation: A class member declared protected becomes a private
member of subclass.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Which of these is correct way of inheriting class A by class B?
a) class B + class A {}
b) class B inherits class A {}
c) class B extends A {}
d) class B extends class A {}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: c

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Which two classes use the Shape class correctly?
A. public class Circle implements Shape { private int radius; }
B. public abstract class Circle extends Shape { private int
radius; }
C. public class Circle extends Shape { private int radius; public
void draw(); }
D. public abstract class Circle implements Shape { private int
radius; public void draw(); }
E. public class Circle extends Shape { private int radius; public
void draw() { /* code here */ } }
F. public abstract class Circle implements Shape { private int
radius; public void draw() { /* code here */ } }

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
a) B,E
b) A,C
c) C,E
d) T,H

Answer: a
Explanation: If one is extending any class, then they should use extends
keyword not implements.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class A
{
int i;
void display()
{
System.out.println(i);
}
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class inheritance_demo
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
a) 0
b) 1
c) 2
d) Compilation Error

Answer: c
Explanation: Class A & class B both contain display() method, class B
inherits class A, when display() method is called by object of class B,
display() method of class B is executed rather than that of Class A.
output:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class A
{
int i;
}
class B extends A
{
int j;
void display()
{
super.i = j + 1;
System.out.println(j + " " + i);
}
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
a) 2 2
b) 3 3
c) 2 3
d) 3 2

Answer: c
$ javac inheritance.java
$ java inheritance
23

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Which inheritance in java programming is not supported
A) Multiple inheritance using classes
B) Multiple inheritance using interfaces
C) Multilevel inheritance
D) Single inheritance

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: A

NOTE:
Java does not support multiple inheritance of classes but it
supports multiple inheritance for interfaces. Means, a class cannot
inherit more than one class but it can inherit and implement multiple
interfaces.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
If class B is subclassed from class A then which is the correct
syntax
A) class B:A{}
B) class B extends A{}
C) class B extends class A{}
D) class B implements A{}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: B

Below is the example


class A{
}

//Class B is subclassed from class A


class B extends A{

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
A class member declared protected becomes member of subclass of
which type?
A. public member
B. private member
C. protected member
D. static member

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: B

A class member declared protected becomes private member of


subclass.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Multiple inheritance means,
(a) one class inheriting from more super classes
(b) more classes inheriting from one super class
(c) more classes inheriting from more super classes
(d) None of the above
(e) (a) and (b) above.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer : A

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Which one of the following is not true?
(a) A class containing abstract methods is called an abstract class.
(b) Abstract methods should be implemented in the derived class.
(c) An abstract class cannot have non-abstract methods.
(d) A class must be qualified as ‘abstract’ class, if it contains one
abstract method.
(e) None of the above.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: C

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The fields in an interface are implicitly specified as,
(a) static only
(b) Protected
(c) private
(d) both static and final
(e) none of the above.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: D

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Which of the following is true?
(a) A finally block is executed before the catch block but after the try
block.
(b) A finally block is executed, only after the catch block is executed.
(c) A finally block is executed whether an exception is thrown or not.
(d) A finally block is executed, only if an exception occurs.
(e) None of the above.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: C

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
What is the output of the following program:
public class testmeth
{
static int i = 1;
public static void main(String args[])
{
System.out.println(i+” , “);
m(i);
System.out.println(i);
}
public void m(int i)
{
i += 2;
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
(a) 1 , 3
(b) 3 , 1
(c) 1 , 1
(d) 1 , 0
(e) none of the above.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: C

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Inheritance in Java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Inheritance:

Inheritance in Java is the concept of create new classes that are


built upon existing classes. When you inherit from an existing class,
you can reuse methods and fields of the parent class.

Inheritance represents the IS-A relationship which is also


known as a parent-child relationship.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Usage of Inheritance:

Method Overriding
Code Reusability.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Terms used in Inheritance:

Class: A class is a template or blueprint from which objects are


created.

Sub Class/Child Class: Subclass is a class which inherits the


other class. It is also called a derived class, extended class, or child
class.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a base class or a
parent class.

Reusability: Reusability is a mechanism which facilitates you


to reuse the fields and methods of the existing class when you create a
new class. You can use the same fields and methods already defined in
the previous class.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class
that derives from an existing class. The meaning of "extends" is to increase
the functionality.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Inheritance (Subclass and Superclass)
In Java, it is possible to inherit attributes and methods from
one class to another.
Two categories of inheritance concepts,

• subclass (child) - the class that inherits from another class


• superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Inheritance Example
Salary is the subclass and Employee is the superclass. The
relationship between the two classes is Salary IS-A Employee. It
means that Salary is a type of Employee.

In this example, Salary object can access the field of own class as well
as of Employee class i.e. code reusability.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Employee {

public void display() {


System.out.println("Employee Name : XYZ");
}

class Salary extends Employee {


public void salary() {
System.out.println("May month salary : 50000");
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Main {
public static void main(String[] args) {

Salary sal = new Salary();


sal.display();
sal.salary();

}
}
Output:
Employee Name : XYZ
May month salary : 50000

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Types of inheritance in java
Three types of inheritance in java,
single
multilevel
hierarchical.

In java programming, multiple and hybrid inheritance is supported


through interface only.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Single Inheritance:
When a class inherits another class, it is known as a single
inheritance

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Car
{
void model()
{
System.out.println("Car Model Name: XYZ");}
}
class Price extends Car
{
void display()
{
System.out.println("Price of the car: 700000");}
}
class Main{
public static void main(String args[]){
Price p = new Price();
p.model();
p.display();
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
Car Model Name: XYZ
Price of the car: 700000

In the above example, Price class inherits the Car class, so there
is the single inheritance.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel
inheritance.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Car
{
void model()
{
System.out.println("Car Model Name: XYZ");
}
}
class Price extends Car
{
void display()
{
System.out.println("Price of the car: 700000");
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Colour extends Price{
void colour()
{
System.out.println("Colour of the car: Black");
}
}
class Main{
public static void main(String args[]){
Colour C = new Colour();
C.model();
C.display();
C.colour();
}}
Output:
Car Model Name: XYZ
Price of the car: 700000
Colour of the car: Black

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Hierarchical Inheritance
When two or more classes inherits a single class, it is known
as hierarchical inheritance.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Car
{
void model()
{
System.out.println("Car Model Name: XYZ");
}
}
class Price extends Car
{
void display()
{
System.out.println("Price of the car: 700000");
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Colour extends Car{
void colour()
{
System.out.println("Colour of the car: Black");
}
}
class Main{
public static void main(String args[]){
Colour C = new Colour();
C.model();
//C.display();//Error
C.colour();
}}

Output:
Car Model Name: XYZ
Colour of the car: Black

In the example, Price and Colour classes inherits the Car class, so there is hierarchical
inheritance.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Multiple inheritance
 Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple


inheritance.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple


inheritance is not supported in java.
Multiple inheritance can cause ambiguity.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output:
Compile Time Error

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The final Keyword:

If you don't want other classes to inherit from a class, use


the final keyword.

If you try to access a final class, Java will generate an error:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
final class Vehicle {
...
}

class Car extends Vehicle {


...
}
Outut:
Car.java:8: error: cannot inherit from final Vehicle
class Car extends Vehicle {
^
1 error)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ’s

1. Which of this keyword must be used to inherit a class?


a) super
b) this
c) extent
d) extends

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: d

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. A class member declared protected becomes a member of subclass of
which type?
a) public member
b) private member
c) protected member
d) static member

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: b
Explanation: A class member declared protected becomes a private
member of subclass.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Which of these is correct way of inheriting class A by class B?
a) class B + class A {}
b) class B inherits class A {}
c) class B extends A {}
d) class B extends class A {}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: c

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Which two classes use the Shape class correctly?
A. public class Circle implements Shape { private int radius; }
B. public abstract class Circle extends Shape { private int
radius; }
C. public class Circle extends Shape { private int radius; public
void draw(); }
D. public abstract class Circle implements Shape { private int
radius; public void draw(); }
E. public class Circle extends Shape { private int radius; public
void draw() { /* code here */ } }
F. public abstract class Circle implements Shape { private int
radius; public void draw() { /* code here */ } }

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
a) B,E
b) A,C
c) C,E
d) T,H

Answer: a
Explanation: If one is extending any class, then they should use extends
keyword not implements.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class A
{
int i;
void display()
{
System.out.println(i);
}
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class inheritance_demo
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
a) 0
b) 1
c) 2
d) Compilation Error

Answer: c
Explanation: Class A & class B both contain display() method, class B
inherits class A, when display() method is called by object of class B,
display() method of class B is executed rather than that of Class A.
output:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class A
{
int i;
}
class B extends A
{
int j;
void display()
{
super.i = j + 1;
System.out.println(j + " " + i);
}
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
a) 2 2
b) 3 3
c) 2 3
d) 3 2

Answer: c
$ javac inheritance.java
$ java inheritance
23

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Which inheritance in java programming is not supported
A) Multiple inheritance using classes
B) Multiple inheritance using interfaces
C) Multilevel inheritance
D) Single inheritance

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: A

NOTE:
Java does not support multiple inheritance of classes but it
supports multiple inheritance for interfaces. Means, a class cannot
inherit more than one class but it can inherit and implement multiple
interfaces.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
If class B is subclassed from class A then which is the correct
syntax
A) class B:A{}
B) class B extends A{}
C) class B extends class A{}
D) class B implements A{}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: B

Below is the example


class A{
}

//Class B is subclassed from class A


class B extends A{

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
A class member declared protected becomes member of subclass of
which type?
A. public member
B. private member
C. protected member
D. static member

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: B

A class member declared protected becomes private member of


subclass.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Multiple inheritance means,
(a) one class inheriting from more super classes
(b) more classes inheriting from one super class
(c) more classes inheriting from more super classes
(d) None of the above
(e) (a) and (b) above.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer : A

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Which one of the following is not true?
(a) A class containing abstract methods is called an abstract class.
(b) Abstract methods should be implemented in the derived class.
(c) An abstract class cannot have non-abstract methods.
(d) A class must be qualified as ‘abstract’ class, if it contains one
abstract method.
(e) None of the above.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: C

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The fields in an interface are implicitly specified as,
(a) static only
(b) Protected
(c) private
(d) both static and final
(e) none of the above.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: D

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Which of the following is true?
(a) A finally block is executed before the catch block but after the try
block.
(b) A finally block is executed, only after the catch block is executed.
(c) A finally block is executed whether an exception is thrown or not.
(d) A finally block is executed, only if an exception occurs.
(e) None of the above.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: C

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
What is the output of the following program:
public class testmeth
{
static int i = 1;
public static void main(String args[])
{
System.out.println(i+” , “);
m(i);
System.out.println(i);
}
public void m(int i)
{
i += 2;
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
(a) 1 , 3
(b) 3 , 1
(c) 1 , 1
(d) 1 , 0
(e) none of the above.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Answer: C

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Access Modifiers in Java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Modifier:
As the name suggests access modifiers in Java helps to restrict
the scope of a class, constructor , variable , method or data member.

We divide modifiers into two groups:


• Access Modifiers - controls the access level
• Non-Access Modifiers - do not control access level, but provides
other functionality

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Access Modifier:
The access modifiers in Java specifies the accessibility or scope
of a field, method, constructor, or class. We can change the access level
of fields, constructors, methods, and class by applying the access
modifier on it.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Four types of access modifires:

Modifier Description

declarations are visible only within


Default
the package (package private)

declarations are visible within the


Private
class only

declarations are visible within the


Protected
package or all subclasses

Public declarations are visible everywhere

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Private:
The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.

Default:
The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Protected:
The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the
child class, it cannot be accessed from outside the package.

Public:
The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package
and outside the package.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Understanding Java Access Modifiers

Access within class within package outside outside


Modifier package by package
subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Private

• Methods, variables, and constructors that are declared private can


only be accessed within the declared class itself.
• Private access modifier is the most restrictive access level. Class and
interfaces cannot be private.
• Variables that are declared private can be accessed outside the class,
if public getter methods are present in the class.
• Using the private modifier is the main way that an object
encapsulates itself and hides data from the outside world.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
//using class from different package with
//private modifier
package p1;

class A
{
private void display()
{
System.out.println("GeeksforGeeks");
}
}

class B
{
public static void main(String args[])
{
A obj = new A();
//trying to access private method of another class
obj.display();
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:

error: display() has private access in A obj.display();

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
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

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
same package.

In this example, we will create two packages and the classes in


the packages will be having the default access modifiers and we will try
to access a class from one package from a class of second package.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
//Java program to illustrate default modifier
package p1;

//Class Geeks is having Default access modifier


class Geek
{
void display()
{
System.out.println("Hello World!");
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
//Java program to illustrate error while
//using class from different package with
//default modifier
package p2;
import p1.*;

//This class is having default access modifier


class GeekNew
{
public static void main(String args[])
{
//accessing class Geek from package p1
Geeks obj = new Geek();

obj.display();
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:

Compile time error

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
protected:

The protected access modifier is specified using the


keyword protected.The methods or data members declared as
protected are accessible within same package or sub classes in
different package.

In this example, we will create two packages p1 and p2. Class A


in p1 is made public, to access it in p2. The method display in class A is
protected and class B is inherited from class A and this protected
method is then accessed by creating an object of class B.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
//Java program to illustrate
//protected modifier
package p1;

//Class A
public class A
{
protected void display()
{
System.out.println("Hello World");
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
//Java program to illustrate
//protected modifier
package p2;
import p1.*; //importing all classes in package p1

//Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:

Hello World

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
public:

• The public access modifier is specified using the keyword public


• The public access modifier has the widest scope among all other
access modifiers.
• Classes, methods or data members which are declared as public
are accessible from every where in the program. There is no
restriction on the scope of a public data members.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
//Java program to illustrate
//public modifier
package p1;
public class A
{
public void display()
{
System.out.println("Hello World");
}
}
package p2;
import p1.*;
class B
{
public static void main(String args[])
{
A obj = new A;
obj.display();
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:

Hello world

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Important Points:
o If other programmers use your class, try to use the most restrictive access
level that makes sense for a particular member. Use private unless you
have a good reason not to.
o Avoid public fields except for constants.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Abstraction & Interfaces in Java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Abstraction

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Abstraction in Java
Data Abstraction is the process of identifying only the required
characteristics of an object ignoring the irrelevant details.

Example, when we ride a bike, we only know about how to ride


bikes but can not know about how it work? And also we do not know
the internal functionality of a bike.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Ways to achieve Abstraction

There are two ways to achieve abstraction in java


1. Abstract class (0 to 100%)
2. Interface (100%)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Abstract class in Java

A class which is declared with the abstract keyword is known as


an abstract class in Java. It can have abstract and non-abstract
methods (method with the body)

abstract class A{}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Points to Remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change
the body of the method.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Abstract Method in Java

A method which is declared as abstract and does not have


implementation is known as an abstract method.

Syntax:
abstract void printStatus();//no method body and abstract

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Abstract classes and Abstract methods :
• An abstract class is a class that is declared with abstract keyword.
• An abstract method is a method that is declared without an
implementation.
• An abstract class may or may not have all abstract methods. Some of
them can be concrete methods
• Any class that contains one or more abstract methods must also be
declared with abstract keyword.
• There can be no object of an abstract class. That is, an abstract class
can not be directly instantiated with the new operator.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
When to use abstract classes and abstract methods with an
example
Define a superclass that declares the structure of a given
abstraction without providing a complete implementation of every
method.

For example, We are doing Mathematical calculation such as addition,


multiplication and so on.., with the use of abstract class and abstract
method.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
abstract class Mathematics
{

// these are abstract methods


abstract double cal();

class add extends Mathematics


{
int a=5;
int b=5;

// @Override
double cal() {
return a+b;
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Mul extends Mathematics{

double x=5;
double y=5;

//@Override
double cal() {
return x*y;
}

}
public class Main
{
public static void main(String[] args)
{
Mathematics M1 = new add();
Mathematics M2 = new Mul();

}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
10
25

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example of Abstract class that has an abstract method
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
running safely

In this example, Bike is an abstract class that contains only one


abstract method run. Its implementation is provided by the Honda
class.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Another example of Abstract class in java
abstract class Car{
abstract void display();
}
//In real scenario, implementation is provided by others i.e. unknown
by end user
class model extends Car{
void display(){System.out.println("Car Model name: XYZ");}
}
class price extends Car{
void display(){System.out.println("Car price is 800000");}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
//In real scenario, method is called by programmer or user
class Main{
public static void main(String args[]){
Car c1 = new model();
Car c2=new price();
c1.display();
c2.display();
}
}
Output:
Car Model name: XYZ
Car price is 800000

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Abstract class having constructor, data member and methods

An abstract class can have a data member, abstract method,


method body (non-abstract method), constructor, and even main()
method.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
//Example of an abstract class that has abstract and non-abstract
methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Output:
bike is created
running safely..
gear changed

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Rule:
If there is an abstract method in a class, that class must be
abstract.

class Bike12{
abstract void run();
}
Output: Compile time error
Rule:
If you are extending an abstract class that has an abstract
method, you must either provide the implementation of the method or
make this class abstract.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Encapsulation vs Data Abstraction

• Encapsulation is data hiding(information hiding) while Abstraction


is detail hiding(implementation hiding).
• While encapsulation groups together data and methods that act
upon the data, data abstraction deals with exposing the interface to
the user and hiding the details of implementation.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Advantages of Abstraction

• It reduces the complexity of viewing the things.


• Avoids code duplication and increases reusability.
• Helps to increase security of an application or program as only
important details are provided to the user

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Interfaces
Interface in Java
An interface in Java is a blueprint of a class. It has static
constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction


and multiple inheritance in Java.
Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in an
interface.
• Since Java 9, we can have private methods in an interface.
Use of Java interface
There are mainly three reasons to use interface. They are given
below,
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple
inheritance.
• It can be used to achieve loose coupling.
Declaration of Interfaces:

An interface is declared by using the interface keyword. It


provides total abstraction; means all the methods in an interface are
declared with the empty body, and all the fields are public, static and
final by default.
Syntax:

interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
A real-world example:

Let’s consider the example of vehicles like bicycle, car,


bike………, they have common functionalities. So we make an interface
and put all these common functionalities. And lets Bicycle, Bike, car
….etc implement all these functionalities in their own class in their own
way.
import java.io.*;

interface Vehicle {

// all are the abstract methods.


void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}
class Bicycle implements Vehicle{

int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear){

gear = newGear;
}
public void printStates() {
System.out.println("speed: " + speed
+ " gear: " + gear);
}
}

class Bike implements Vehicle {

int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear){

gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){

speed = speed + increment;


}

// to decrease speed
@Override
public void applyBrakes(int decrement){

speed = speed - decrement;


}
public void printStates() {
System.out.println("speed: " + speed
+ " gear: " + gear);
}

}
class GFG {

public static void main (String[] args) {

// creating an inatance of Bicycle


// doing some operations
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
System.out.println("Bicycle present state :");
bicycle.printStates();

// creating instance of the bike.


Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);

System.out.println("Bike present state :");


bike.printStates();
}
}
Output:

Bicycle present state :


speed: 2 gear: 2
Bike present state :
speed: 1 gear: 1
Java 8 Interface Improvement
Since Java 8, interface can have default and static methods
which is discussed later.

Internal addition by the compiler


The Java compiler adds public and abstract keywords before
the interface method. Moreover, it adds public, static and final
keywords before data members.
The relationship between classes and interfaces
As shown in the figure given below, a class extends another
class, an interface extends another interface, but a class implements
an interface.
Java Interface Example
interface printable{
void print();
}
class Java8 implements printable{
public void print(){System.out.println("Hello");}
}
class Main{
public static void main(String args[]){
Java8 obj = new Java8();
obj.print();
}
}
Output:
Hello

In this example, the Printable interface has only one method,


and its implementation is provided in the Java8 class.
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface
extends multiple interfaces, it is known as multiple inheritance.
interface Print{
void print();
}
interface Show{
void show();
}
class Multiple implements Print,Show{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
}
class Main{
public static void main(String args[]){
Multiple obj = new Multiple();
obj.print();
obj.show();
}
}
Multiple inheritance is not supported through class in java,
but it is possible by an interface, why?

Multiple inheritance is not supported in the case


of class because of ambiguity. However, it is supported in case of an
interface because there is no ambiguity.
interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
Output:
Hello

As you can see in the above example, Printable and Showable


interface have same methods but its implementation is provided by
class TestTnterface1, so there is no ambiguity.
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome

A class implements an interface, but one interface extends


another interface.
Java 8 Default Method in Interface
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Output:
drawing rectangle
default method

Since Java 8, we can have method body in interface. But we


need to make it default method
Marker or Tagged interface:
An interface which has no member is known as a marker or
tagged interface, for example, Serializable, Cloneable, Remote, etc.

Syntax:
public interface Serializable{
}
Nested Interface in Java

An interface i.e. declared within another interface or class is


known as nested interface. The nested interfaces are used to group
related interfaces so that they can be easy to maintain. The nested
interface must be referred by the outer interface or class. It can't be
accessed directly.
Points to remember for nested interfaces
There are given some points that should be remembered by the java
programmer.

• Nested interface must be public if it is declared inside the interface


but it can have any access modifier if declared within the class.
• Nested interfaces are declared static implicitely
Syntax of nested interface which is declared within the
interface

interface interface_name{
...
interface nested_interface_name{
...
}
}
Syntax of nested interface which is declared within the class

class class_name{
...
interface nested_interface_name{
...
}
}
Example of nested interface which is declared within the interface
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message{
public void msg(){System.out.println("Hello nested interface");}

public static void main(String args[]){


Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
}
}
Output:hello nested interface
Example of nested interface which is declared within the class
class A{
interface Message{
void msg();
}
}

class TestNestedInterface2 implements A.Message{


public void msg(){System.out.println("Hello nested interface");}

public static void main(String args[]){


A.Message message=new TestNestedInterface2();//upcasting here
message.msg();
}
}
Output:hello nested interface
Difference between abstract class and interface
Abstract class and interface both are used to achieve
abstraction where we can declare the abstract methods. Abstract class
and interface both can't be instantiated.
Abstract class Interface

1) Abstract class can have abstract and Interface can have only
non-abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.
6) An abstract class can extend An interface can extend another
another Java class and implement Java interface only.
multiple Java interfaces.
7) An abstract class can be An interface can be implemented
extended using keyword using keyword "implements".
"extends".
8) A Java abstract class can Members of a Java interface are
have class members like private, public by default.
protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Example of abstract class and interface in Java
//Creating interface that has 4 methods
interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}

//Creating abstract class that provides the implementation of one method


of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
//Creating subclass of abstract class, now we need to provide the implementation of
rest of the methods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}

//Creating a test class that calls the methods of A interface


class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:
I am a
I am b
I am c
I am d
MCQ’s

1. Which of these keywords are used to define an abstract class?


a) abst
b) abstract
c) Abstract
d) abstract class
Answer: b
2. Which of these is not abstract?
a) Thread
b) AbstractList
c) List
d) None of the Mentioned
Answer: a
Explanation: Thread is not an abstract class.
3. If a class inheriting an abstract class does not define all of its
function then it will be known as?
a) Abstract
b) A simple class
c) Static class
d) None of the mentioned
Answer: a
Explanation: Any subclass of an abstract class must either implement
all of the abstract method in the superclass or be itself declared
abstract.
4. Which of these is not a correct statement?
a) Every class containing abstract method must be declared abstract
b) Abstract class defines only the structure of the class not its
implementation
c) Abstract class can be initiated by new operator
d) Abstract class can be inherited
Answer: c
Explanation: Abstract class cannot be directly initiated with new
operator, Since abstract class does not contain any definition of
implementation it is not possible to create an abstract object.
5. Which of these packages contains abstract keyword?
a) java.lang
b) java.util
c) java.io
d) java.system
Answer: a
6. What will be the output of the following Java code?
class A
{
public int i;
private int j;
}
class B extends A
{
void display()
{
super.j = super.i + 1;
System.out.println(super.i + " " + super.j);
}
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error
Answer: d
Explanation: Class contains a private member variable j, this cannot be
inherited by subclass B and does not have access to it.
7. What will be the output of the following Java code?
class A
{
public int i;
public int j;
A()
{
i = 1;
j = 2;
}
}
class B extends A
{
int a;
B()
{
super();
}
}
class super_use
{
public static void main(String args[])
{
B obj = new B();
System.out.println(obj.i + " " + obj.j)
}
}
a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error
Answer: a
Explanation: Keyword super is used to call constructor of class A by
constructor of class B. Constructor of a initializes i & j to 1 & 2
respectively.
8. What will be the output of the following Java code?
class A
{
int i;
void display()
{
System.out.println(i);
}
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class method_overriding
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 0
b) 1
c) 2
d) Compilation Error
Answer: c
Explanation: class A & class B both contain display() method, class B
inherits class A, when display() method is called by object of class B,
display() method of class B is executed rather than that of Class A.
Which among the following best defines abstraction?
a) Hiding the implementation
b) Showing the important data
c) Hiding the important data
d) Hiding the implementation and showing only the features
Answer: d
Explanation: It includes hiding the implementation part and showing
only the required data and features to the user. It is done to hide the
implementation complexity and details from the user. And to provide a
good interface in programming.
Hiding the implementation complexity can ____________
a) Make the programming easy
b) Make the programming complex
c) Provide more number of features
d) Provide better features
Answer: a
Explanation: It can make programming easy. The programming need
not know how the inbuilt functions are working but can use those
complex functions directly in the program. It doesn’t provide more
number of features or better features.
Class is _________ abstraction.
a) Object
b) Logical
c) Real
d) Hypothetical
Answer: b
Explanation: Class is logical abstraction because it provides a logical
structure for all of its objects. It gives an overview of the features of an
object.
Object is ________ abstraction.
a) Object
b) Logical
c) Real
d) Hypothetical
Answer: c
Explanation: Object is real abstraction because it actually contains
those features of class. It is the implementation of overview given by
class. Hence the class is logical abstraction and its object is real.
Abstraction gives higher degree of ________
a) Class usage
b) Program complexity
c) Idealized interface
d) Unstable interface
Answer: c
Explanation: It is to idealize the interface. In this way the programmer
can use the programming features more efficiently and can code better.
It can’t increase the program complexity, as the feature itself is made to
hide it.
Abstraction can apply to ____________
a) Control and data
b) Only data
c) Only control
d) Classes
Answer: a
Explanation: Abstraction applies to both. Control abstraction involves
use of subroutines and control flow abstraction. Data abstraction
involves handling pieces of data in meaningful ways.
Which among the following can be viewed as combination of
abstraction of data and code.
a) Class
b) Object
c) Inheritance
d) Interfaces
Answer: b
Explanation: Object can be viewed as abstraction of data and code. It
uses data members and their functioning as data abstraction. Code
abstraction as use of object of inbuilt class.
Abstraction principle includes___________
a) Use abstraction at its minimum
b) Use abstraction to avoid longer codes
c) Use abstraction whenever possible to avoid duplication
d) Use abstraction whenever possible to achieve OOP
Answer: c
Explanation: Abstraction principle includes use of abstraction to avoid
duplication (usually of code). It this way the program doesn’t contain
any redundant functions and make the program efficient.
Higher the level of abstraction, higher are the details.
a) True
b) False
Answer: b
Explanation: Higher the level of abstraction, lower are the details. The
best way to understand this is to consider a whole system that is highest
level of abstraction as it hides everything inside. And next lower level
would contain few of the computer components and so on.
Encapsulation and abstraction differ as ____________
a) Binding and Hiding respectively
b) Hiding and Binding respectively
c) Can be used any way
d) Hiding and hiding respectively
Answer: a
Explanation: Abstraction is hiding the complex code. For example, we
directly use cout object in C++ but we don’t know how is it actually
implemented. Encapsulation is data binding, as in, we try to combine a
similar type of data and functions together.
In terms of stream and files ____________
a) Abstraction is called a stream and device is called a file
b) Abstraction is called a file and device is called a stream
c) Abstraction can be called both file and stream
d) Abstraction can’t be defined in terms of files and stream
Answer: a
Explanation: Abstraction is called stream to provide a level of
complexity hiding, for how the files operations are actually done. Actual
devices are called file because in one way or another, those can be
considered as single entity and there is nothing hidden.
If two classes combine some private data members and provides public
member functions to access and manipulate those data members.
Where is abstraction used?
a) Using private access specifier for data members
b) Using class concept with both data members and member functions
c) Using public member functions to access and manipulate the data
members
d) Data is not sufficient to decide what is being used
Answer: c
Explanation: It is the concept of hiding program complexity and actual
working in background. Hence use of public member functions
illustrates abstraction here.
A phone is made up of many components like motherboard, camera,
sensors and etc. If the processor represents all the functioning of
phone, display shows the display only, and the phone is represented as
a whole. Which among the following have highest level of abstraction?
a) Motherboard
b) Display
c) Camera
d) Phone
Answer: d
Explanation: Phone as a whole have the highest level of abstraction.
This is because the phone being a single unit represents the whole
system. Whereas motherboard, display and camera are its components.
Which among the following is not a level of abstraction?
a) Logical level
b) Physical level
c) View level
d) External level
Answer: d
Explanation: Abstraction is generally divided into 3 different levels,
namely, logical, physical and view level. External level is not defined in
terms of abstraction.
Using higher degree of abstraction __________
a) May get unsafe
b) May reduce readability
c) Can be safer
d) Can increase vulnerability
Answer: c
Explanation: It will make the code safer. One may think it reduces the
readability, but the fact is, it actually helps us understand the code
better. We don’t have to read the complex code which is of no use in
understanding the program.
What is the syntax of abstract class in java?
A. abstract A{}
B. abstract class A
C. abstract class A{}
D. abstract class A[]
Ans : C
Explanation:The syntax of abstract class in java is abstract class A{}.
What will be output for the folllowing code?
abstract class Bank {

private abstract void withdraw(); // Line 1


abstract void deposit();
public void balance(){} //Line 2
}
class office extends Bank{ // Line 3

void deposit() { // Line 4


// TODO Auto-generated method stub

}
}
A. Compilation error in Line 1(abstract method cannot be private)
B. Compilation error in Line 2(abstract class cannot have concrete
method)
C. Compilation error in Line 3(abstract class cannot be extended)
D. Compilation error in Line 4(deposit method should have public
access modifier)
Ans : A
Explanation: Yes, you are right!! As private method can’t be overridden
and abstract method should be overridden in child classes, so this line
will give compilation error.
Which of these is not a correct statement?
A. Every class containing abstract method must be declared abstract
B. Abstract class defines only the structure of the class not its
implementation
C. Abstract class can be initiated by new operator
D. Abstract class can be inherited
Ans : C
Explanation: Abstract class cannot be directly initiated with new
operator, Since abstract class does not contain any definition of
implementation it is not possible to create an abstract object.
A method which is declared as abstract and does not have
implementation is known as an _____________?
A. Abstract Interface
B. Abstract Thread
C. Abstract List
D. abstract Method
Ans : D
Explanation: A method which is declared as abstract and does not have
implementation is known as an abstract method.
Aggregation
Aggregation in Java

If a class have an entity reference, it is known as Aggregation.


Aggregation represents HAS-A relationship.
Consider a situation, Employee object contains many
informations such as id, name, emailId etc. It contains one more object
named address, which contains its own informations such as city, state,
country, zipcode etc. as given below.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}

In such case, Employee has an entity reference address, so


relationship is Employee HAS-A address.
UML
• Aggregation is very similar to composition. The only logical
difference is aggregation is a weaker relationship.
• Therefore, UML representations are also very similar. The only
difference is the diamond is empty:
Source Code
In Java, we can model aggregation with a plain old reference:

class Wheel {}

class Car {
List<Wheel> wheels;
}
The member can be any type of class, except a non-static inner class.
In the code snippet above both classes have their separate
source file. However, we can also use a static inner class:

class Car {
List<Wheel> wheels;
static class Wheel {}
}
Note that Java will create an implicit reference only in non-static inner
classes. Because of that, we have to maintain the relationship manually
where we need it:

class Wheel {
Car car;
}

class Car {
List<Wheel> wheels;
}
Why use Aggregation?
For Code Reusability.

When use Aggregation?


Code reuse is also best achieved by aggregation when there is
no is-a relationship.
Inheritance should be used only if the relationship is-a is
maintained throughout the lifetime of the objects involved; otherwise,
aggregation is the best choice.
Simple Example of Aggregation
class Operation{
int square(int n){
return n*n;
}
}

class Circle{
Operation op;//aggregation
double pi=3.14;

double area(int radius){


op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}

public static void main(String args[]){


Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
Meaningful example of Aggregation

In this example, Employee has an object of Address, address


object contains its own informations such as city, state, country etc. In
such case relationship is Employee HAS-A address.
Address.java
public class Address {
String city,state,country;

public Address(String city, String state, String country) {


this.city = city;
this.state = state;
this.country = country;
}

}
Emp.java
public class Emp {
int id;
String name;
Address address;

public Emp(int id, String name,Address address) {


this.id = id;
this.name = name;
this.address=address;
}

void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country);
}
public static void main(String[] args) {
Address address1=new Address("gzb","UP","india");
Address address2=new Address("gno","UP","india");

Emp e=new Emp(111,"varun",address1);


Emp e2=new Emp(112,"arun",address2);

e.display();
e2.display();

}
}
Output:
111 varun
gzb UP india
112 arun
gno UP india
Association & Aggregation in Java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Association

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introduction:
Objects have relationships between them, both in real life and
in programming. Sometimes it's difficult to understand or implement
these relationships.
In this session, we'll focus on Java's take on three sometimes
easily mixed up types of relationships: composition, aggregation, and
association.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Association:

Association in Java is a connection between two separate


classes that is set up through their objects. Although, Java association
can balance, one-to-one, one-to-many, and many-to-many
relationships. It defines the multiplicity between objects.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
There are two types of Association

• Aggregation
• Composition

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The association relationship indicates that a class knows about
another class. It can be described as a “has-a” relationship between
classes. The relationship between the classes can be bi-directional.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
For example, if we talk about the association between a teacher
and a student, multiple students can associate with a single teacher and a
single student is also associated with multiple teachers but both can be
created or deleted independently. So, when a teacher leaves the school, we
don’t need to remove any students, and when a student leaves the school,
we don’t need to remove any teachers.

So, in the above example, the teacher has many students and vice
versa, connectes to various objects. Thus, we can say the association in
Java follows a many-to-many relationship.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Association
Association is the weakest relationship between the three. It
isn't a “has-a” relationship, none of the objects are parts or
members of another.
Association only means that the objects “know” each
other. For example, a mother and her child.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
UML
In UML, we can mark an association with an arrow:

If the association is bidirectional, we can use two arrows, an arrow with


an arrowhead on both ends, or a line without any arrowheads:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
We can represent a mother and her child in UML, then:
`

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Source Code
In Java, we can model association the same way as aggregation:

class Child {}

class Mother {
List<Child> children;
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
But wait, how can we tell if a reference means aggregation or
association?
Well, we can't. The difference is only logical: whether one of the
objects is part of the other or not.
Also, we have to maintain the references manually on both ends as we did
with aggregation:
class Child {
Mother mother;
}

class Mother {
List<Child> children;
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Java Association Example
package com.dataflair.association;
class Teacher
{
private String name;
Teacher(String name)
{
this.name = name;
}
public String getTeacherName()
{
return this.name;
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Student
{
private String name;
Student(String name)
{
this.name = name;
}
public String getStudentName()
{
return this.name;
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class AssociationDemo
{
public static void main (String[] args)
{
Teacher teacherObj = new Teacher("Rahul Sir");
Student studentObj = new Student("Renuka");
System.out.println(studentObj.getStudentName() +
" is Student of " + teacherObj.getTeacherName());
}
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Types of Association in Java
There are two types of association in Java

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introduction to Java
Introduction to JAVA

Write a program to add two numbers


To make the work easy, Let’s go step by step approach before writing actual program
1. Pseudocode
2. Algorithm
3. Flowchart
Algorithm

● Set of step-by-step instructions that perform a specific task or operation


● Algorithm is written using natural language NOT programming language
Algorithms for adding two numbers :
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Pseudocode
● Pseudocode is a Set of instructions that mimic programming language
instructions
● It uses short phrases to write code for programs before you actually create it
in a specific language.
Pseudocode for adding two numbers :
➔ Ask the user for two values
➔ Save the input in num1 and num2 variables
➔ Perform num1 + num2
➔ Save the result in num3 variable
➔ Print num3 variable
Flow Chart

● Visual program design tool


● Semantic symbols describe operations to be performed
Represents the start and the end of a flowchart -

Used for input and output operation -

Indicates the flow of logic by connecting symbols -

Used for decision making between two or more alternatives -


Try It Out !!

Write a program to find smallest number of two numbers

1. Pseudocode
2. Algorithm
3. Flowchart
Flow Chart
Start

Input
a, b

true false
If a<b

Print a Print b

stop
Algorithm

Algorithms for finding smallest of two numbers :


Step 1: Start
Step 2: Declare variables a, b.
Step 3: Read values a and b.
Step 4: Use condition if to check the a<b .
Step 5: if true print a
Step 6: else print b
Pseudocode

Pseudocode for finding smallest of two numbers :


➔ Ask the user for two values
➔ Save the input in a and b variables
➔ Check whether a < b
➔ If true print a else print b
Introduction to Programming

What is Programming Language?


A programming language is a set of commands, instructions, and other syntax
use to create a software program

Who is a Programmer?
Programmers are the person who writes programs in a specific computer
programming language.
Through constructor
TYPES OF PROGRAMMING

There are two types of programming languages:


1. Low level language
a) Machine language
b) Assembly language

2. High level language


a) Procedural-Oriented language
b) Problem-Oriented language
c) Object-Oriented language
c) Natural language
Through constructor
Machine language

• Sometimes referred to as machine code or object code,


• Machine language is a collection of binary digits or bits that the computer
reads and interprets. Machine language is the only language a computer is
capable of understanding.

Example: Below is an example of machine language (binary) for the text "Hello
World".

01001000 01100101 01101100 01101100 01101111 00100000


01010111 01101111 01110010 01101100 01100100
Through constructor
Assembly language

● They are often used to write operating systems

● The Java Bytecode Assembler (or simply Assembler) is a program that


converts code written in "Java Assembly Language" into a valid Java.class
file

● most compilers convert source code directly to machine code,


Through constructor
Object Oriented Programming Language

● Object Oriented programming (OOP) is a programming relies on the concept


of classes and objects.
● It is used to structure a software program into simple, reusable pieces of
code blueprints (usually called classes).
● There are many object-oriented programming languages including Java,
JavaScript, C++ and Python.
Through constructor
Procedure-oriented language

● Procedural Programming involves writing down a list of instructions to tell


the computer what it should do step-by-step to finish the task at hand.

● the procedural code is the one that directly instructs a device on how to
finish a task in logical steps.
Through constructor
Problem-oriented language

A computer language designed to handle a particular class of problem.


Example:
● COBOL was designed for business (Common Business-Oriented Language)
● FORTRAN for scientific (Formula Translation)
● GPSS for simulation.
Through constructor
Natural language

● natural language refers to a human language such as English, Russian,


German, or Japanese as distinct from the typically artificial command or
programming language with which one usually talks to a computer
Through constructor
Functional programming

What is Functional Programming :


Functional programming (FP) is the process of building software by composing
pure functions.
Each function takes in an input value and returns a consistent output value
without altering or being affected by the program state.

Disadvantages of Functional Programming:


● Writing pure functions is easy, but combining them into a complete
application is where things get hard.
● For many people, recursion doesn’t feel natural.
● Pure functions and I/O don’t really mix.
● Purely functional vocabularies work slower than the hash tables
Introduction to JAVA

Why to study JAVA


Through constructor
Introduction to JAVA

● JAVA developed by Sun Microsystems Inc in 1991, later acquired by Oracle


Corporation.
● Developed by James Gosling and Patrick Naughton.
● It is a simple programming language. Writing, compiling and debugging a
program is easy in java.
Introduction to JAVA

● Some of the applications which uses JAVA as one of the languages


Features of JAVA
Interview Questions !!

● One of the features of JAVA, it is secured language. Why?


● What is the difference between JAVA and C++ ?
Through constructor
Introduction to JAVA

3 PHASES OF PROGRAM EXECUTION


1) Writing - java programmer
2) Compilation - javac compiler.
I. Javac is the primary java compiler included in java development kit (JDK).
II. It takes java program as input and generates java byte code as output.
3) Run phase :
JVM executes the bytecode generated by compiler.
Through constructor
BYTE Code

I. javac compiler of JDK compiles the java source code into bytecode
so that it can be executed by JVM.
II. The bytecode is saved in a .class file by compiler.
Through constructor
JAVA Development Kit - (JDK)

JDK includes
I. JRE (Java Runtime Environment)
II. compilers
III. various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed
on your computer.
Through constructor
JAVA Runtime Environment(JRE)

I. JRE is a part of JDK


II. When you have JRE installed on your system, you can run a java program
however you won’t be able to compile it.
III. When you only need to run a java program on your computer, you would
only need JRE.
Interview Question !!

What is JDK, JRE and JVM ?


Interview Question !!

Why JAVA is called Platform Independent?

Each operating system has different JVM, however the output they produce
after execution of byte code is same across all operating systems.
Interview Question !!

Why JAVA is both Compiler and Interpreter ?


JAVA Basic Structure

public class Welcome \\welcome is a class name


{
public static void main(String[ ] args)
{
System.out.println("Welcome to JAVA Class");
}
}
Interview Question !!

Explain public static void main(String[ ] args)


Question: 01

Java source code is compiled into

A. Source Code
B. Byte Code
C. .obj
D. .exe
Question: 02

Which of the tool is used to compile java


code ?

A. Java
B. javac
C. javadoc
D. jdk
Question: 03

Choose a Single Line Comment in Java


Language below?

A. //Some comments
B. Some comments//
C. */Some comments/*
D. /*Some comments*/
Question: 04

JAVA is what type of Programming Language ?

A. Assembly Level Language


B. Object Oriented Language
C. Binary Language
D. Machine Language
Question: 05
A. class CLASSNAME
Choose the correct syntax for declaring a
Java class below. {
}
A. CLASSNAME class
{
}
A. class CLASSNAME;
{
}
A. CLASS CLASSNAME
{
}
/ethnuscodemithra Ethnus /ethnus /code_mithra
Codemithra

https://learn.codemithra.com

codemithra@ethnus.com +91 7815 095 +91 9019 921


095 340
Introduction to Java
Introduction to JAVA

Write a program to add two numbers


To make the work easy, Let’s go step by step approach before writing actual program
1. Pseudocode
2. Algorithm
3. Flowchart
Algorithm

● Set of step-by-step instructions that perform a specific task or operation


● Algorithm is written using natural language NOT programming language
Algorithms for adding two numbers :
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Pseudocode
● Pseudocode is a Set of instructions that mimic programming language
instructions
● It uses short phrases to write code for programs before you actually create it
in a specific language.
Pseudocode for adding two numbers :
➔ Ask the user for two values
➔ Save the input in num1 and num2 variables
➔ Perform num1 + num2
➔ Save the result in num3 variable
➔ Print num3 variable
Flow Chart

● Visual program design tool


● Semantic symbols describe operations to be performed
Represents the start and the end of a flowchart -

Used for input and output operation -

Indicates the flow of logic by connecting symbols -

Used for decision making between two or more alternatives -


Try It Out !!

Write a program to find smallest number of two numbers

1. Pseudocode
2. Algorithm
3. Flowchart
Flow Chart
Start

Input
a, b

true false
If a<b

Print a Print b

stop
Algorithm

Algorithms for finding smallest of two numbers :


Step 1: Start
Step 2: Declare variables a, b.
Step 3: Read values a and b.
Step 4: Use condition if to check the a<b .
Step 5: if true print a
Step 6: else print b
Pseudocode

Pseudocode for finding smallest of two numbers :


➔ Ask the user for two values
➔ Save the input in a and b variables
➔ Check whether a < b
➔ If true print a else print b
Introduction to Programming

What is Programming Language?


A programming language is a set of commands, instructions, and other syntax
use to create a software program

Who is a Programmer?
Programmers are the person who writes programs in a specific computer
programming language.
Through constructor
TYPES OF PROGRAMMING

There are two types of programming languages:


1. Low level language
a) Machine language
b) Assembly language

2. High level language


a) Procedural-Oriented language
b) Problem-Oriented language
c) Object-Oriented language
c) Natural language
Through constructor
Machine language

• Sometimes referred to as machine code or object code,


• Machine language is a collection of binary digits or bits that the computer
reads and interprets. Machine language is the only language a computer is
capable of understanding.

Example: Below is an example of machine language (binary) for the text "Hello
World".

01001000 01100101 01101100 01101100 01101111 00100000


01010111 01101111 01110010 01101100 01100100
Through constructor
Assembly language

● They are often used to write operating systems

● The Java Bytecode Assembler (or simply Assembler) is a program that


converts code written in "Java Assembly Language" into a valid Java.class
file

● most compilers convert source code directly to machine code,


Through constructor
Object Oriented Programming Language

● Object Oriented programming (OOP) is a programming relies on the concept


of classes and objects.
● It is used to structure a software program into simple, reusable pieces of
code blueprints (usually called classes).
● There are many object-oriented programming languages including Java,
JavaScript, C++ and Python.
Through constructor
Procedure-oriented language

● Procedural Programming involves writing down a list of instructions to tell


the computer what it should do step-by-step to finish the task at hand.

● the procedural code is the one that directly instructs a device on how to
finish a task in logical steps.
Through constructor
Problem-oriented language

A computer language designed to handle a particular class of problem.


Example:
● COBOL was designed for business (Common Business-Oriented Language)
● FORTRAN for scientific (Formula Translation)
● GPSS for simulation.
Through constructor
Natural language

● natural language refers to a human language such as English, Russian,


German, or Japanese as distinct from the typically artificial command or
programming language with which one usually talks to a computer
Through constructor
Functional programming

What is Functional Programming :


Functional programming (FP) is the process of building software by composing
pure functions.
Each function takes in an input value and returns a consistent output value
without altering or being affected by the program state.

Disadvantages of Functional Programming:


● Writing pure functions is easy, but combining them into a complete
application is where things get hard.
● For many people, recursion doesn’t feel natural.
● Pure functions and I/O don’t really mix.
● Purely functional vocabularies work slower than the hash tables
Introduction to JAVA

Why to study JAVA


Through constructor
Introduction to JAVA

● JAVA developed by Sun Microsystems Inc in 1991, later acquired by Oracle


Corporation.
● Developed by James Gosling and Patrick Naughton.
● It is a simple programming language. Writing, compiling and debugging a
program is easy in java.
Introduction to JAVA

● Some of the applications which uses JAVA as one of the languages


Features of JAVA
Interview Questions !!

● One of the features of JAVA, it is secured language. Why?


● What is the difference between JAVA and C++ ?
Through constructor
Introduction to JAVA

3 PHASES OF PROGRAM EXECUTION


1) Writing - java programmer
2) Compilation - javac compiler.
I. Javac is the primary java compiler included in java development kit (JDK).
II. It takes java program as input and generates java byte code as output.
3) Run phase :
JVM executes the bytecode generated by compiler.
Through constructor
BYTE Code

I. javac compiler of JDK compiles the java source code into bytecode
so that it can be executed by JVM.
II. The bytecode is saved in a .class file by compiler.
Through constructor
JAVA Development Kit - (JDK)

JDK includes
I. JRE (Java Runtime Environment)
II. compilers
III. various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed
on your computer.
Through constructor
JAVA Runtime Environment(JRE)

I. JRE is a part of JDK


II. When you have JRE installed on your system, you can run a java program
however you won’t be able to compile it.
III. When you only need to run a java program on your computer, you would
only need JRE.
Interview Question !!

What is JDK, JRE and JVM ?


Interview Question !!

Why JAVA is called Platform Independent?

Each operating system has different JVM, however the output they produce
after execution of byte code is same across all operating systems.
Interview Question !!

Why JAVA is both Compiler and Interpreter ?


JAVA Basic Structure

public class Welcome \\welcome is a class name


{
public static void main(String[ ] args)
{
System.out.println("Welcome to JAVA Class");
}
}
Interview Question !!

Explain public static void main(String[ ] args)


Question: 01

Java source code is compiled into

A. Source Code
B. Byte Code
C. .obj
D. .exe
Question: 02

Which of the tool is used to compile java


code ?

A. Java
B. javac
C. javadoc
D. jdk
Question: 03

Choose a Single Line Comment in Java


Language below?

A. //Some comments
B. Some comments//
C. */Some comments/*
D. /*Some comments*/
Question: 04

JAVA is what type of Programming Language ?

A. Assembly Level Language


B. Object Oriented Language
C. Binary Language
D. Machine Language
Question: 05
A. class CLASSNAME
Choose the correct syntax for declaring a
Java class below. {
}
A. CLASSNAME class
{
}
A. class CLASSNAME;
{
}
A. CLASS CLASSNAME
{
}
/ethnuscodemithra Ethnus /ethnus /code_mithra
Codemithra

https://learn.codemithra.com

codemithra@ethnus.com +91 7815 095 +91 9019 921


095 340
Data types
What you’ll learn

● Need of data types


● Introduction to data types
● Classification of data types
● Size and range of primitive data types
● Non primitive data types
● Difference between primitive and non primitive
● Type casting
● Variables, Methods
● Types of variables & methods
● Ways to access the variables & methods
● Code snippets
● Real life scenario
Need of data types

● Java - strongly typed language


● Operations are type-checked by compiler
● To achieve type compatibility
● To allocate the respective memory space
● To be more robust
Introduction to data types

Specifies the type and size of the values to be stored in a variable / Identifier

Two broader classification for datatypes


● Primitive data types - includes byte, short, int, long, float, double,
boolean and char

● Non-primitive data types - such as String, Arrays and Classes


Classification of data types
Size and range of primitive data types

Data Type Size Description


byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
Stores whole numbers from -2,147,483,648 to
int 4 bytes 2,147,483,647
Stores whole numbers from -9,223,372,036,854,775,808 to
long 8 bytes 9,223,372,036,854,775,807
Stores fractional numbers. Sufficient for storing 6 to 7
float 4 bytes decimal digits
Stores fractional numbers. Sufficient for storing 15
double 8 bytes decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter
Code snippet 1

public class Main {


public static void main(String[] args) {
byte Num = 127;
System.out.println(Num);
}
}
Code snippet 2

public class Main {


public static void main(String[] args) {
byte Num = 128;
System.out.println(Num);
}
}
Code snippet 3

public class Main {


public static void main(String[] args) {
short Num = 5000;
System.out.println(Num);
}
}
Code snippet 4

public class Main {


public static void main(String[] args) {
short Num = 509864700;
System.out.println(Num);
}
}
Code snippet 5

public class Main {


public static void main(String[] args) {
int Num = 5986745;
System.out.println(Num);
}
}
Code snippet 6

public class Main {


public static void main(String[] args) {
long Num = 50000000l;
System.out.println(Num);
}
}
Code snippet 7

public class Main {


public static void main(String[] args) {
long Num = 50000000;
System.out.println(Num);
}
}
Code snippet 8

public class Main {


public static void main(String[] args) {
float Num = 5.75f;
System.out.println(Num);
}
}
Code snippet 9

public class Main {


public static void main(String[] args) {
double Num = 19.99d;
System.out.println(Num);
}
}
Code snippet 10

A floating point number can also be a scientific number with an "e" to


indicate the power of 10

public class Main {


public static void main(String[] args) {
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
}
}
Code snippet 11

public class Main {


public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
}
}
Code snippet 12

The char data type is used to store a single character. The character
must be surrounded by single quotes.

public class Main {


public static void main(String[] args) {
char Letter = 'B';
System.out.println(Letter);
}
}
Code snippet 13

public class Main {


public static void main(String[] args) {
char a = 65, b = 66, c = 67;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(a+b+c);
}
}
Code snippet 14

The String data type is used to store a sequence of characters (text).


String values must be surrounded by double quotes.

public class MyClass {


public static void main(String[] args) {
String greeting = "Hello World";
System.out.println(greeting);
}
}
Through constructor
Non primitive data types

● Non-primitive data types are called reference types because they refer to
objects.

● Some of the reference types are pre defined such as String, Array.
● String s = “Hello world”;
● String is a non primitive data type (pre defined class).
● User defined non primitive data types can also be created with classes &
Interfaces.
Through constructor
Differences

● Primitive types are predefined (already defined) in Java. Non-primitive types


can be created by the programmers.

● Non-primitive types can be used to call methods to perform certain


operations, while primitive types cannot.
● A primitive type has always a value, while non-primitive types can be null.
● A primitive type starts with a lowercase letter, while non-primitive types
starts with an uppercase letter.
● The size of a primitive type depends on the data type, while non-primitive
types have all the same size.
Through constructor
Typecasting

● Changing one type of information to the other type.


● It can be implied for both primitive and as well as non primitive data types.

Two types:
● Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
● Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Through constructor
When to go for typecasting?

Consider
int i = 10; // type matching statement
String s = “Hello world”; //type matching statement
char c = ‘a’; //type matching statement
double d = 87.97545; //type matching statement
But,
double d1= 50; //type mismatching statement
int i1 = 89.98; //type mismatching statement

Thus, whenever there are type mismatching statements, perform typecasting to


change the value to the respective data type.
Through constructor
Example

double d1= 50; //type mismatching statement 1


int i1 = 89.98; //type mismatching statement 2

Typecasting:

Widening for statement 1: conversion of smaller value to large


type
(automatically taken care by
compiler)
System.out. println(d1); //50.0

Narrowing for statement 2: conversion of large value to smaller


type
Through constructor
WIDENING CASTING

Widening casting is done automatically when passing a smaller size type to a


larger size type
Example
public class Main{
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt;
System.out.println(myDouble);
System.out.println(myInt);
}
}
Through constructor
NARROWING CASTING

Narrowing casting is done automatically when passing a larger size type to a


smaller size type
Example
public class Main{
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble;
System.out.println(myDouble);
System.out.println(myInt);
}
}
Through constructor
Code snippet

public class Test {


public static void main(String[] args) {
int i = 98756;
int i1 = 9.0;
double d = i;
System.out.println(i+" "+d);
double d1 = 56.897d;
int i2 = (int) d1;
System.out.println(d1+" "+i2);
int a = 9;
float f = a/2; // 9/2 = 4.0
System.out.println(f);
char c = 'A';//65
int n = c+1;//66
char c1 = (char) n;
System.out.println(c1); }}
Through constructor
Variables

Containers to store the values


Variable type and value must match
int a = 100; // int is the data type, a is the variable name, 100 is the value
1. begin your variable names with a letter, not "$" or "_".
2. the dollar sign character, by convention, is never used at all
3. variable's name with "_", this practice is discouraged. White space is not permitted.
4. use full words instead of cryptic abbreviations
5. must not be a keyword or reserved word.
6. If the name you choose consists of only one word, spell that word in all lowercase letters. If
it consists of more than one word, capitalize the first letter of each subsequent word

String name = “John”;


String companyName = “Ethnus”;
Through constructor
Types

1. Instance Variables (Non-Static Fields) :


● objects store their individual states in "non-static fields", that is, fields
declared without the static keyword
● Non-static fields are also known as instance variables
1. Class Variables (Static Fields) :
● A class variable is any field declared with the static modifier
● The compiler that there is exactly one copy of this variable in existence,
regardless of how many times the class has been instantiated.
Through constructor
Types

1. Local Variables :
● method will often store its temporary state in local variables.
● The syntax for declaring a local variable is similar to declaring a field (for example, int
count = 0;).
● There is no special keyword designating a variable as local.

1. Parameters
● The signature for the main method is public static void main(String[] args).
● The args variable is the parameter to this method.
● The parameters are always classified as "variables" not "fields".
Declaring Many Variable

public class Main {


public static void main(String[] args) {
int x = 5, y = 10, z = 15;
System.out.println(x + y + z);
}
}
Java Method

● A method is a block of code which only runs when it is called.


● You can pass data, known as parameters, into a method.
● Methods are used to perform certain actions, and they are also known as
functions.

Why use methods?


To reuse code: define the code once, and use it many times.
Java Methods
● A method must be declared within a class.
● It is defined with the name of the method, followed by parentheses ().
Example
public class MyClass {
void myMethod() {
// code to be executed
}
}
Call a Method

public class Main {


static void myMethod() {
System.out.println("Method executed!");
}

public static void main(String[] args) {


myMethod();
}
}
Multiple Call
public class Main {
static void myMethod() {
System.out.println("Method executed!");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}
Java Method parameter
● Information can be passed to methods as parameter.

● Parameters act as variables inside the method.


● Parameters are specified after the method name, inside the
parentheses.
● You can add as many parameters as you want, just separate them
with a comma
Types of methods

Pre-defined methods
Example → System.out. println();
User defined methods
Example → void displayInformation(){ }
Ways to access static and non-static methods

Static methods → access using the class name


Non static methods → access using the object / reference variable
Example

public class MyClass {


static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
Multiple Parameter
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
Example

public class Main {


static int myMethod(int x) {
return 5 + x;
}

public static void main(String[] args) {


System.out.println(myMethod(3));
}
}
Predict the Output

public class Main {


static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


System.out.println(myMethod(5, 3));
}
}
Predict the Output

public class Main {


static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


int z = myMethod(5, 3);
System.out.println(z);
}
}
Example
public class Main {
static int plusMethodInt(int x, int y) {
return x + y;
}
static double plusMethodDouble(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
}
Through constructor
Real life scenario!

Problem statement :

Create a simple Java project which will


contain two source files, one for storing the
aadhar card details, another for storing the
PAN details. Choose the appropriate data
types for storing the respective details. Use
the constructor to initialize the variables
and a non static method to display the
information to the user.Link both PAN and
aadhar details and notify the same to the
user.
Through constructor
Sample output
Question: 01

Which of the following is not an valid


declaration of an array?

A. int [ ] a = new int [3];


B. int a [ ] [ ] = new int [3] [3]
C. int [ ] [ ] a = new int [3] [ ];
D. int [ ] [ ] a = new int [ ] [3];
Question: 02

Which of the following line will not compile


assuming b1, b2 and b3 are byte variables
and J is Int variable?

A. b1 = 3;
B. b3 = b1 * b2;
C. b3 = 10 * b1;
D. b2 = (byte) j;
Question: 03

public class Test {


public static void main(String[] args)
{
System.out.print("Y" + "O");
System.out.print('L' + 'O');
} A. YOLO
B. YO155
}
Question: 04

public class Test {


public static void main(String[] args) {
System.out.print("Y" + "O");
System.out.print('L');
System.out.print('O');
} A. YO7679
B. YOLO
}
Question: 05

public class Main


{
public static void main(String[] args) {
int[] initializedArrays = new int[]{50, 2, 44}; A. 2
System.out.println(initializedArrays[1]); 100
initializedArrays[1] = 100; A. 2
2
System.out.println(initializedArrays[1]);
A. Error
}
}
Question: 06

public class Test {


public static void main(String[] argv){
char ch = 'c';
int num = 88;
ch = num; A. Error
System.out.println(ch); B. 88
}
C. C
D. X
}
Question: 07

class Main{
public static void main(String[] args) {
float f = 10.5f;
int a = (int) f;
A. 10.5
System.out.println(f); 10
System.out.println(a); A. Error
} B. 10
} 10
Question: 08

Integer Data type does not include following


primitive data type ____________.

A. long
B. byte
C. short
D. double
Question: 09

class mainclass {
public static void main(String args[]) {
boolean var1 = true;
boolean var2 = false;
A. 0
if (var1) B. 1
System.out.println(var1); C. true
else D. false
System.out.println(var2);
}
}
Question: 10

class booloperators {
public static void main(String args[]) {
boolean var1 = true;
boolean var2 = false;
System.out.println((var1 & var2)); A. 0
} B. 1
C. true
}
D. false
Question: 11

class asciicodes {
public static void main(String args[]) {
char var1 = 'A';
char var2 = 'a'; A. 162
System.out.println((int) var1 + " " + B. 65 97
(int) var2);
C. 67 95
}
} D. 66 98
Question: 12

class A {
public static void main(String args[]) {
byte b;
int i = 258;
A. 258 325 325
double d = 325.59; B. 258 326 326
b = (byte) i; C. 2 325 69
System.out.print(b); D. Error
i = (int) d;
System.out.print(i);
b = (byte) d;
System.out.print(b);
}
}
Question: 13

class A {
public static void main(String args[]) {
int x; A. 10 20 10 100
x = 10;
B. 10 20 10 20
if (x == 10) {
int y = 20; C. 10 20 10 10
System.out.print("x and y: " + x + " " + y);
D. Error
y = x * 2;
}
y = 100;
System.out.print("x and y: " + x + " " + y);
}
}
Question: 14

public class Test {


static void test(float x) {
System.out.print("float");
} A. float
static void test(double x) {
B. double
System.out.print("double");
} C. Compilation Error
public static void main(String[] args) {
test(99.9); D. Exception is thrown at runtime
}
}
Question: 15

public class Test {


public static void main(String[] args) { A. 8 7
int i = 010;
B. 10 7
int j = 07;
System.out.println(i); C. Compilation fails with an error at
System.out.println(j); line 3
}
} D. Compilation fails with an error at
line 5
E. None of these
Question: 16

public class MyClass {


public static void main(String[] args) {
int a = 10;
System.out.println(++a++); A. 10
}
B. 11
}
C. 12
D. Compilation Error
Question: 17

public class Main {


public static void main(String[] args) {
int a = 5 + 5 * 2 + 2 * 2 + (2 * 3);
System.out.println(a); A. 138
}
B. 264
}
C. 41
D. 25
Question: 18

class char_increment {
public static void main(String args[])
{ A. E U
char c1 = 'D';
char c2 = 84; B. UE
c2++; C. VE
c1++;
System.out.println(c1 + " " + c2); D. UF
}
}
Question: 19

class conversion {
public static void main(String args[]) {
double a = 295.04;
int b = 300; A. 38 43
byte c = (byte) a;
B. 39 44
byte d = (byte) b;
System.out.println(c + " " + d); C. 295 300
}
D. 295.04 300
}
Question: 20

class mainclass {
public static void main(String args[]) {
char a = 'A';
a++; A. 66
System.out.print((int) a);
B. 67
}
} C. 65
D. 64
Question: 21

What is the incorrect statement about non-


primitive data types or user-defined data types? A. Non-primitive data types can be
created using the primitive data types.

B. Non-primitive data types can contain


only primitive data types. They can not
contain other non-primitive/user-
defined data types in them.
C. Non-primitive data types can contain
both primitive data types and other
non-primitive/user-defined data types.

D. None of the above


Question: 22

class variable_scope {
public static void main(String args[]) {
int x;
A. 5656
x = 5; {
int y = 6; B. 565
System.out.print(x + " " + y);
} C. Runtime error
System.out.println(x + " " + y);
} D. Compilation error
}
Question: 23

If we have to store the following information


about a student, how many values of from A. 0 Boolean, 1 Characters, 3
each data type group do we need. Floating Point and 3 Integers

B. 1 Boolean, 2 Characters, 2
1. Student name Floating Point and 2 Integers
2. College name
3. Roll Number A. 2 Boolean, 1 Characters, 3
4. Total Marks Floating Point and 1 Integers
5. Percentage
A. 0 Boolean, 5 Characters, 2
6. Height in Feet
Floating Point and 0 Integers
7. Gender
Question: 24

What is not an example of literals?

A. 23.4

B. 198

A. ‘a’

B. None of the above


Question: 25

class array_output
{
public static void main(String args[])
{
int array_variable [] = new int[10]; A. 02468
for (int i = 0; i < 10; ++i) B. 12345
C. 0123456789
{
D. 1 2 3 4 5 6 7 8 9 10
array_variable[i] = i;
System.out.print(array_variable[i] + " ");
i++;
}
}
}
/ethnuscodemithra Ethnus Codemithra /ethnus /code_mithra

https://learn.codemithra.com

codemithra@ethnus.com +91 7815 095 +91 9019 921 340


095
Classes & Objects
What you’ll learn

● Introduction to class and object


● Class diagram
● Class instantiation
● Memory level operations for class & object
● Ways to initialize the instance class members
● Basics of constructors
● this keyword
● Code snippets
● Real time demonstration
Can you name your favorite cricketer?
Describe your favorite cricketer
Segregate the nouns & verbs
List them down

Mahendra Singh Dhoni Batting


39 Years Wicket Keeping
Brown Leading the team
Batsman Strategic decision making
Indian Focus & determining
Let’s get technically started!
Class and object

What is Class?
● A class is a template or blueprint that For Example:
is used to create objects. A car is an object. It has states
● A class consists of data members and (name, color, model) and its
methods. behavior (changing gear, applying
brakes).
What is Object?
● Any real-world entity that has state
and its behavior.
Class & object

● A blueprint from which you can


create an individual object
● Any entity that has:
○ State
○ Behavior
○ Identity
● State --> data member
● Behavior --> method
● Identity --> unique Id(name)
Class diagram
Compartments

Class Name

Class Variables

Class Methods
Defining a class

● Access modifiers: A class can be public or default


● class keyword: class keyword is used to create a class.
● Class name: The name should begin with an initial letter ( refer naming
convention).
● Body: The class body surrounded by braces, { }.
Cricketer

class Cricketer{ void cricketerDetails(){

//Instance variables System.out.println(name);

String name = “Dhoni”; System.out.println(age);

int age = 39; System.out.println(color);

String color = “Brown”; System.out.println(role);

String role = “Batsman”; System.out.println(nationality);

String nationality = “Indian”; }//end of method


}//end of class
Class Instantiation

● Object is an instance of a class


● Process of creating an object from a class is called instantiation.
● Now that you have defined a new class type --> Cricketer, it is time to instantiate
an object of that type.
● new keyword is used to initialize/create an object.
● new operator is followed by a call to a constructor, which initializes the new
object.

Example: name = Dhoni


Cricketer c = new Cricketer(); age = 39
color = Brown
role = Batsman c
nationality = Indian

Heap area
Create an object
Cricketer - code snippet

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


String name = “Dhoni”; System.out.println(“main method
int age = 39; started”);
String color = “Brown”; Cricketer c = new Cricketer();
String role = “Batsman”; c.cricketerDetails();
String nationality= “Indian”; System.out.println(“main method
void cricketerDetails(){ ended”);
System.out.println(name); }//end of main method
System.out.println(age); }//end of Cricketer class
System.out.println(color);
System.out.println(role);
System.out.println(nationality);
}//end of criketerDetails method
Create an object
Cricketer - code snippet
Create an object
Know the difference!

Example:01 Example:02
public class Demo{ public class Demo {
int x; int x;
} public static void main(String[] args) {
Demo myObj1 = new Demo();
class TestDemo{ Demo myObj2 = new Demo();
public static void main(String[] myobj1.x = 24;
args) { myobj2.x = 55;
Demo myObj = new Demo(); System.out.println(myObj1.x);
myobj.x = 40; System.out.println(myObj2.x);
System.out.println(myObj.x); }
} }
}
Ways to initialize the instance variables

● By reference variable

● By method

● By constructor
Through reference variable
By reference variable

class Student { class Main {


int id; public static void main(String args[]) {
String name; Student s1 = new Student();
} s1.id = 101;
s1.name = "John";
System.out.println(s1.id + " " + s1.name);
}
}
Through method
By method

class Student {
int rollno;
String name;
void insertRecord(int r, String n) {
rollno = r;
name = n;
}
void displayInformation() {
System.out.println(rollno + " " + name);
}
}
By method - continued.,

class Main {

public static void main(String args[])


{
Student s1 = new Student();
Student s2 = new Student();
s1.insertRecord(111, "Karan");
s2.insertRecord(222, "Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Constructor

A special method
constructs/initializes the values at the time of object creation.
No return type
Has same name as class name
Automatically invoked when the object is created
name = null
Cricketer c = new Cricketer(); object creation & age = 0
color = null
constructor
role = null
invocation nationality =
null
C
Types of constructors

● Default:
1. java compiler creates a default constructor if your class
doesn't have any explicit constructor
2. Always no-argument constructor
● User defined
1. Is explicitly written in the class
To initialize the instance members with user-defined values
1. Zero-parameterized / No-argument constructor
2. Parameterized constructor
By User defined No-arg constructor

class Employee {
int id;
String name;
float salary;
Employee() {
System.out.println(“user defined no-argument
constructor executed”);
}
void display() {
System.out.println(id + " " + name + " " + salary);
}
}
Through constructor
By user defined no-argument constructor

public class Main {


public static void main(String[] args) {

Employee e1 = new Employee();


Employee e2 = new Employee();

e1.display();
e2.display();

}
}
By User defined parameterized constructor

class Employee {
int id;
String name;
float salary;
Employee(int id, String name, float salary) {
id = id;
name = name;
salary = salary;
}
void display() {
System.out.println(id + " " + name + " " +
salary);
}
}
Through constructor
Passing values for parameterized constructor

public class Main {


public static void main(String[] args) {

Employee e1 = new Employee(101, "ajeet", 45000);


Employee e2 = new Employee(102, "irfan", 25000);
Employee e3 = new Employee(103, "nakul", 55000);

e1.display();
e2.display();
e3.display();
}
}
Through constructor
“this” keyword

● Refers to the current object


● Eliminates the confusion between Instance members and parameters
which are local to the constructors / methods
Employee(int id,String name,float salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
Through constructor
“this” keyword

● “this” refers to the Employee class object


● “this” keyword is used for the instance variable
initialization
● Values passed to the constructor are local to it

● Local values --> id, name, salary


● Instance variables --> this.id, this.name,
this.salary
Through constructor
Knowledge check

Try predicting the outputs for


the given code snippets !

Ensure proper analysis of


codes before guessing the
output.
Through constructor
Knowledge check

class Company {
String name;
public static void main(String[] args) {
System.out.println(new Company().name);
}
}
Through constructor
Knowledge check

class Company {
String name;
public static void main(String[] args) {
Company c = new Company();
Company c1 = c;
c1.name = “Ethnus”;
c = null;
System.out. println(c.name);
}
}
Through constructor
Knowledge check

public class Company{


String name;
public static void main(String[] args) {
Company c1 = new Company();
c1.name = "Ethnus";
System.out.println(c1.name);
c1 = new Company();
System.out.println(c1.name);
}

}
Through constructor
Knowledge check

public class Company {


String name;
public static void main(String[] args) {
Company c1 = new Company();
c1.name = "Ethnus";
Company c2 = c1;
c1 = null;
System.out.println(c2.name);
new Company();
Company c3;
c3.name = "Ethnus";
System.out.println(c3.name);}}

}
Through constructor
Knowledge check

public class Program1 {


String name;
void changeRef(Program1 that) {
that = this;
System.out.println(this.name);
}
public static void main(String[] args) {
Program1 c1 = new Program1();
c1.name = "Ethnus";
Program1 c2 = new Program1();
c2.name = "Aptimithra";
c1.changeRef(c2);
System.out.println(c1.name);
System.out.println(c2.name);}}
}
Through constructor
Knowledge check

public class Company2 {


String name;
void changeRef(Company2 that, Company2 someCompany) {
someCompany = that;
someCompany.name = this.name;
that = someCompany;}
public static void main(String[] args) {
Company2 c1 = new Company2();
c1.name = "Ethnus";
Company2 c2 = new Company2();
c2.name = "Aptimithra";
c1.changeRef(c2, c1);
System.out.println(c1.name);
System.out.println(c2.name);}}
Through constructor
Knowledge check

class Company {
String name;
void changeRef(Company that) {
that.name = this.name;
}
public static void main(String[] args) {
Company c1 = new Company();
c1.name = "Ethnus";
Company c2 = new Company();
c2.name = "Aptimithra";
c1.changeRef(c2);
System.out.println(c1.name);
System.out.println(c2.name);}
Through constructor
Knowledge check

class Company {
String name;
void changeRef(Company that) {
that.name = this.name;
that = null;
}
public static void main(String[] args) {
Company c1 = new Company();
c1.name = "Ethnus";
Company c2 = new Company();
c2.name = "Aptimithra";
c1.changeRef(c2);
System.out.println(c1.name);
System.out.println(c2.name);}
}
}
Through constructor
Code snippet

public class Main {


static int x = 10;
public static void main(String[] args) {
Main obj = new Main();
Main obj1 = new Main();
obj.x = x + 1;
System.out.println(obj.x);
System.out.println(obj1.x);
} }
Through constructor
Real time example!

● The localStorage object stores data with


no expiration date.
● The data will not be deleted when the
browser is closed.
● It will be available the next day, week, or
year.
● The localStorage property is read-only.
Through constructor
Real time example!
Through constructor
Real time example!

DEMO
Question: 01

Which of the following statement(s) is/are


correct?
X: A class is like a blue print and we can A. X only
create as many objects using that class B. Y only
Y: Every object should belong to a class, C. Both X and Y are correct
since we cannot create objects without D. Both X and Y are incorrect
a class
Question: 02

Which of the following class declaration is


correct?

/* X */ /* Y */ A. X only
class Student { CLASS Student { B. Y only
String String C. X and Y both are correct
name; name;
D. X and Y both are incorrect
int marks; int marks;
char char
section; section;
} }
Question: 03

Which of the following is a valid


declaration of an object of class Student?
1. Student obj = new Student; A. 1 only
2. Student obj = new Student();
3. obj = new Student(); B. 2 only
4. new Student obj; C. 1 & 2
D. 3 & 4
Question: 04

What will be the output of the following


program?
class Apple {
int weight; A. 1
public static void main(String args[]) { B. 2
Apple a1 = new Apple(); C. Error
Apple a2 = new Apple(); D. null
a1.weight = 1;
a2.weight = 2;
a2 = a1;
System.out.println(a2.weight);
}}
Question: 05

class Car {
int Wheels;
void swap(Car other) {
other = this; } }
public class Main { A. 48
public static void main(String[] args) { B. 44
Car C1 = new Car(); C. 84
C1.Wheels = 4; D. 88
Car C2 = new Car();
C2.Wheels = 8;
C2.swap(C1);
System.out.print(C1.Wheels + "");
System.out.print(C2.Wheels);
}
}
Question: 06

class Car {
int Wheels;
void swap(Car other) {
other.Wheels = this.Wheels;
}} A. 48
public class Main { B. 44
public static void main(String[] args) { C. 84
Car C1 = new Car(); D. 88
C1.Wheels = 4;
Car C2 = new Car();
C2.Wheels = 8;
C1.swap(C2);
System.out.println(C1.Wheels);
System.out.println(C2.Wheels);
}}
Question: 07

class A { public class Increment {


int i = 0; public static void
A(int i) { main(String[] args) {
this.i = i + A a = new A(5);
4; a.increment(); A. i=1
} a.operate(); B. i = 103
void increment() a = new A(a.i); C. i = 55
{ a.operate(); D. Compilation Error
i = this.i + a.increment();
1;
} System.out.printl
void n("i = " + a.i);
operate() }
{ }
i *= 3;
Question: 08

class Test {
int i;
}
class Main { A. 0
public static void main(String args[]) { B. Garbage Value
Test t; C. Compilation Error
System.out.println(t.i); D. Runtime Error
}
Question: 09

public class Final {


final int assign = 30;
public static void main(String[] args)
{
final int result = 20; A. 20 20 25
final int assign; B. 20 30 25
C. Compilation Error
Final f = new Final();
D. Runtime Error
assign =20;
System.out.println(assign);
System.out.println(f.assign);

System.out.println(f.process(result));
}
int process(int a) {
Question: 10

public class InitializationTest {


int number;
public void InitializationTest(int
A. 5
number) {
B. Compile time Error since no default
this.number = number;
constructor
System.out.println(number);
C. Compile time Error since no
}
parameterized constructor
public static void main(String[] args) {
D. Compilation Error or Runtime Error for
InitializationTest obj1, obj2;
some other reason
obj1 = new InitializationTest();
obj2 = new InitializationTest(5);
}
}
Question: 11

class Test {
void start() {
String stra = "do";
String strb = method(stra);
System.out.print(": " + stra + strb);
A. dogood : dogoodgood
}
B. dogood : gooddogood
String method(String stra) {
C. dogood : dodogood
stra = stra + "good";
D. dogood : dogood
System.out.print(stra);
return " good";
} }
class Main {
public static void main(String[] args) {
Test obj = new Test();
obj.start(); } }
Question: 12

class Student { class ReferencesAndObjects {


String name; public static void main(String s[]) {
int marks; Student st1 = new Student();
Student st2;
char section;
st2 = st1;
} st1.name = "Rajesh"; A. Rajesh 87 C Rajesh 87 C
st2.marks = 87; B. rajesh 87 C rajesh 87 C
st1.section = 'C'; C. Rajesh C 87 Rajesh C 87
System.out.println("" + st1.name + D. rajesh C 87 rajesh C 87
"" + st1.marks + "" + st1.section);
System.out.println("" + st2.name +
"" + st2.marks + "" + st2.section);
}}
Question: 13

class Simple { class Demo {


int a = 0; public static void main(String
void incr() { aRgs[]) {
a++; Simple s = new Simple();
} Simple r = new Simple();
void display() { s.incr(); A. a=0a=0
System.out.println(" r.incr(); B. a=1a=1
a = " + a); s.display(); C. a=0a=1
} r.display(); D. a=1a=2
}
}
Question: 14

class PrintA { class OutPut {


int printA; int c;
} public static void main(String[] args) {
class PrintB { PrintA a = new PrintA();
int printB = 5; PrintB c = new PrintB(); A. printA = 0 printB = 5 c = 0
int c; System.out.println("printA = " + B. printA = 0 printB = 5 c =
} a.printA); (some object reference
System.out.println("printB = " + value)
c.printB); C. Compilation Error
System.out.println("c = " + c.c);
D. Runtime Error
}
}
Question: 15
class Student { class ReferencesAndObjects {
String name; public static void main(String s[]) {
int marks; Student st1 = new Student();
char section; Student st2 = new Student(); A. Print using st1 : Rajesh 0 C Print
} st1 = st2; using st2 : null 87
st1.name = "Rajesh";
st2.marks = 87; A. Print using st1 : Rajesh 87 C Print
st1.section = 'C'; using st2 : Rajesh 87 C
System.out.print("Print using st1 : " +
st1.name + " " + st1.marks + " " + A. Print using st1 : null 0 Print using
st1.section); st2 : Rajesh 87 C
System.out.print("Print using st2 : " +
st2.name + " " + st2.marks + " " + A. Compilation Error
st2.section);
}}
Question: 16

class User{
int age;
String name;
} A. Error
public class Main{ B. Null pointer Exception
public static void main(String[] args) { C. 100
User u1=new User(); D. null
u1.name=100;
u1=null;

System.out.println(u1.name);
}
}
Question: 17

class User{
int age;
String name; }
public class Main{
public static void main(String[] args) { A. A
User u1=new User(); B. Null
u1.name="A"; C. Error
User u2=u1; D. C
u2=null;
u2=new User();
u1.name = "c";
u2.name=u1.name;
u1=null;
System.out.println(u2.name);
} }
Question: 18

class User{
int age;
String name;
} A. A
public class Main{ B. B
public static void main(String[] args) { C. Error
User u1=new User(); D. Cannot execute
u1.name="A";
User u2=u1;
u1.name = "B";

System.out.println(u1.name);
}
Question: 19

class User{
int age;
String name;
} A. A
public class Main{ B. Null pointer Exception
public static void main(String[] args) { C. Cannot execute
User u1=new User(); D. null
u1.name="A";
u1=null;
System.out.println(u1.name);
}
}
Question: 20

class User{
int age;
String name;
} A. A
public class Main{ B. Null pointer Exception
public static void main(String[] args) { C. Cannot execute
User u1=new User(); D. null
u1.name="A";
User u2=new User();
u2=u1;
u1=null;

System.out.println(u1.name);
Question: 21

class User{
int age;
String name;
} A. A
public class Main{ B. B
public static void main(String[] args) { C. Error
User u1=new User(); D. u1 address
u1.name="A";
User u2=u1;
u2=new User();
u2.name=”B”;

System.out.println(u1.name);
Question: 22
class Human{
String name;
int age;
Human(String name, int age){
A. Null 0
this.name=name;
B. Adam 32000
this.age=age;
C. Error
} }
D. 32000 Adam
class Main{
public static void main(String args[]){
Human adam = new Human("Adam",32000);
System.out.println(adam.name);
System.out.println(adam.age);
} }
Question: 23
class Human{
String name;
int age; A. method foo
void foo() { method boo
this.boo(); A. method boo
System.out.println("method foo");} method boo
void boo() { A. method foo
System.out.println("method boo"); method foo
A. method boo
} }
method foo
class Main{
public static void main(String args[]){
Human adam = new Human();
adam.foo();
} }
Question: 24
class User{
String name;
void sayHello(User randomUser){
randomUser.name = "HiddenGuy";
A. HiddenGuy
randomUser=null;
B. AwesomeGuy
} }
C. AwesomeGuy HiddenGuy
public class Main{
D. Error
public static void main(String[] args) {
User u1=new User();
u1.name="Awesome Guy";
u1.sayHello(u1);
System.out.println(u1.name);
}
Question: 25
class User{
String name;
String address;
User(String x,String y){ A. X,Y
name=x; B. null
address=y; null
System.out.println(name); A. Error
System.out.println(address); B. name,address
} }
public class Main{
public static void main(String[] args) {
User u1=new User();
}
Question: 26
class Temp{
Temp() {
this(5); A. 15
System.out.println("Inside Temp"); } 5
Temp(int x) { Inside temp
this(5,15); A. 75
System.out.println(x); } 5
Temp(int x,int y) { Inside temp
System.out.println(x * y); A. Error in line number 5. No
}} method found named "this"
public class Main{ B. Inside temp
public static void main(String[] args) {
new Temp();
} }
Question: 27

class User{
String name;
void sayHello(User randomUser){ A. BadGuy
this.name = randomUser.name; BadGuy
} } A. BadGuy
public class Main{ AwesomeGuy
public static void main(String[] args) { A. AwesomeGuy
User u1=new User(); BadGuy
u1.name="Awesome Guy"; A. AwesomeGuy
User u2=new User(); AwesomeGuy
u1.name="Bad Guy";
u1.sayHello(u2);
System.out.println(u1.name);
System.out.println(u2.name);
Question: 28
class Fruit {
String name;
Fruit(String name) {
this.name = name;
} A. null Orange
} B. null null
class Main { C. Error
public static void main(String args[]) { D. Orange
Fruit orange = new Fruit("Orange");
Fruit mango = new Fruit();
System.out.println(mango.name + " " +
orange.name);
}
}
Question: 29
class User {
String name;
public User callMe(User randomUser) {
randomUser = this;
return null;
A. Random Technologies
}}
public class Main { B. Null
public static void main(String[] args) { C. Null pointer Exception
User u1 = new User(); D. Random null
u1.name = "Random";
User u2 = new User();
u2.name = "Technologies";
u2 = u1.callMe(u2);
System.out.println(u1.name + " " + u2.name);
}
}
Question: 30
class User {
int id;
void generateId(int id) {
this.id = id * 5;
}} A. 25 25
public class Main { B. 50 50
public static void main(String[] args) { C. 00
User u1 = new User(); D. 50 0
u1.generateId(5);
User u2 = u1;
u2.generateId(10);
u1 = u2;
System.out.println(u1.id + " " + u2.id);
}}
/ethnuscodemithra Ethnus Codemithra /ethnus /code_mithra

https://learn.codemithra.com

codemithra@ethnus.com +91 7815 095 +91 9019 921


095 340
OPERATORS
Arithmetic

o These are the operators used to perform arithmetic/mathematical operations on

operands. Examples: (+, -, *, /, %,++,--)


class Main {
public static void main(String[] args) {
int a=9,b=4,c;
c=a+b;
System.out.println("a+b"+" "+"="+" "+c);
c=a-b;
System.out.println("a-b"+" "+"="+" "+c);
c=a*b;
System.out.println("a*b"+" "+"="+" "+c);
c=a/b;
System.out.println("a/b"+" "+"="+" "+c);
c=a%b;
System.out.println("a%b"+" "+"="+" "+c);
}
}
Arithmetic
o The operators +, - and * computes addition, subtraction and multiplication
respectively as you might have expected
o In normal calculation, 9/4 = 2.25
o However, the output is 2 in the program
o It is because both variables a and b are integers
o Hence, the output is also an integer
o The compiler neglects the term after decimal point and shows answer 2 instead
of 2.25
o The modulo operator % computes the remainder. When a = 9 is divided by b = 4,
the remainder is 1
o The % operator can only be used with integers
Increment and Decrement
o Java programming has two operators increment ++ and decrement -- to change
the value of an operand (constant or variable) by 1. Increment ++ increases the
value by 1 whereas decrement -- decreases the value by 1. These two operators
are unary operators, meaning they only operate on a single operand

Example :
suppose, a = 5 then,
o ++a; //a becomes 6
o a++; //a becomes 7
o --a; //a becomes 6
o a--; //a becomes 5
Increment and Decrement
o 5 is displayed then, var is increased to 6
o Initially, var = 6. It is increased to 7 then, it is displayed

class Main {
public static void main(String[] args) {
int a =5;
System.out.println(a++);
System.out.println(++a);
}
}
Assignment

o An assignment operator is used for assigning a value to a variable. The most


common assignment operator is =

Operator Example Same as


= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b
Assignment
class Main {
public static void main(String[] args) {
int a = 5, c;
c = a;
System.out.println("c"+" "+"="+" "+c);
c += a;
System.out.println("c"+" "+"="+" "+c);
c -= a;
System.out.println("c"+" "+"="+" "+c);
c *= a;
System.out.println("c"+" "+"="+" "+c);
c /= a;
System.out.println("c"+" "+"="+" "+c);
c %= a;
System.out.println("c"+" "+"="+" "+c);
}
}
Relational
o Relational operators are used for comparison of the values of two operands. For
example: checking if one operand is equal to the other operand or not, an
operand is greater than the other operand or not etc. Some of the relational
operators are (==, > , = , <= )
o A relational operator checks the relationship between two operands. If the
relation is true, it returns 1; if the relation is false, it returns value 0. Relational
operators are used in decision making and loops
Relational

Operator Meaning of Example


Operator
== Equal to 5 == 3 returns 0

> Greater than 5 > 3 returns 1

< Less than 5 < 3 returns 0

!= Not equal to 5 != 3 returns 1

>= Greater than or equal to 5 >= 3 returns 1

<= Less than or equal to 5 <= 3 return 0


Relational
class Main { else
public static void main(String[] args) { System.out.println("a is less than");
int a=10, b=4; if (a < b)
if (a > b) System.out.println("a is less than");
System.out.println("a is greater than"); else
else System.out.println("a is greater than or
System.out.println("a is less than or equal equal to");
to"); if (a <= b)
if (a >= b) System.out.println("a is lesser than or
System.out.println("a is greater than or equal to");
equal to"); else
System.out.println("a is greater than");
Relational

if (a == b)
System.out.println ("a is equal to ");
else
System.out.println("a and b are not equal");
if (a != b)
System.out.println("a is not equal to ");
else System.out.println("a is equal ");
}
}
Logical
o An expression containing logical operator returns either 0 or 1 depending upon
whether expression results true or false. Logical operators are commonly used in
decision making in Java programming

Operator Meaning of Operator Example


&& Logical AND. True only if all If c = 5 and d = 2
operands are true then, expression
((c == 5) && (d >
5)) equals to 0
|| Logical OR. True only if If c = 5 and d = 2
either one operand is true then, expression
((c == 5) || (d > 5))
equals to 1
! Logical NOT. True only if the If c = 5 then,
operand is 0 expression ! (c ==
5) equals to 0
Logical
class Main { if((a == b) && (c < b))
public static void main(String[] args) { {
int a = 5, b = 5, c = 10, result; result=1;
if ((a == b) && (c > b)) System.out.println("(a == b) && (c < b) equals to"+"
{ "+ result);
result=1; }
System.out.println("(a == b) && (c > b) equals to else
"+result); {
} result=0;
else System.out.println("(a == b) && (c > b) equals to"+"
{ "+ result);
result=0; }
System.out.println("(a == b) && (c > b) equals if ((a == b) || (c < b))
to"+" "+ result); {
} result=1;
System.out.println("(a == b) || (c < b) equals to "+"
"+ result);
}
Logical
else else
{ {
result=0; result=0;
System.out.println("(a == b) || (c < b) equals to "+" System.out.println("(a != b) || (c < b) equals to "+" "+
"+ result); result);
} }
if((a != b) || (c < b)) if (!(a != b))
{ {
result=1; result=1;
System.out.println("(a != b) || (c < b) equals to"+" System.out.println("!(a == b) equals to "+" "+ result);
"+ result); }
}
Logical
else
{
result=0;
System.out.println("!(a == b) equals to "+" "+ result);
}
if(!(a == b))
{
result=1;
System.out.println("!(a == b) equals to "+" "+ result);
}
else
{
result=0;
System.out.println("!(a == b) equals to "+" "+ result);
}
}
}
Bitwise
o The Bitwise operators is used to perform bit-level operations on the operands.
The operators are first converted to bit-level and then calculation is performed on
the operands. The mathematical operations such as addition , subtraction ,
multiplication etc
Operator Meaning of Operator
& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right


Bitwise
class Main {
public static void main(String[] args) {
int a = 2, b = 4,c;
c=a & b;
System.out.println("Bitwise AND "+ c);
c= a | b;
System.out.println("Bitwise OR "+c);
c=a >> 1;
System.out.println("Right shift "+ c);
c=a << 1;
System.out.println("Left shift "+ c);
c=a ^ b;
System.out.println("Bitwise exclusive OR "+ c);
c=~a;
System.out.println("Bitwise complement "+ c);
}
}
Comma Operator & SIZE
o Comma operators are used to link related expressions together

int a, c = 5, d;

o The sizeof is an unary operator which returns the size of data (constant,
variables, array, structure etc)
Comma Operator & SIZE
class Main {
public static void main(String[] args) {
int []n= new int[10],a;
float b;
double c;
char d;
System.out.println("Size of int bytes "+(Float.SIZE/8));
System.out.println("Size of float bytes "+(Double.SIZE/8));
System.out.println("Size of char bytes "+(Character.SIZE/8));
System.out.println("Size of double bytes "+(Integer.SIZE/8));
}
}
C Ternary Operator (?:)
o A conditional operator is a ternary operator, that is, it works on 3 operands

The conditional operator works as follows:

o The first expression conditionalExpression is evaluated first. This expression


evaluates to 1 if it's true and evaluates to 0 if it's false
o If conditionalExpression is true, expression1 is evaluated
o If conditionalExpression is false, expression2 is evaluated

conditionalExpression ? expression1 : expression2


C Ternary Operator (?:)
import java.util.Scanner;
class Main {
public static void main(String[] args) {
char February;
int days;
System.out.println("Leap year? enter 1. If not enter any integer: ");
Scanner s=new Scanner(System.in);
February =s.next().charAt(0);
days = (February == '1') ? 29 : 28;
System.out.println("Number of days in February = "+days);
}
}
Operators In Java
Operators In Java

● Operators are special symbols that perform specific operations on operands


and find the result. e.g., +, -, *, >, <=, !.
● These operators help in performing operations like arithmetic operations,
● boolean logical operations, relational operations,assignment operations,
bitwise and ternary operations.
Operators In Java

In the expression 25 + 17, 25 and 17 are the operands where as + is the


operator. So for addition operation, the operator used is + and it needs two
operands. Depending upon the operation the number of operands will be
different. It could be 1 or 2 or 3 operands. For addition it is 2 operands, for unary
minus it is only one operand and for ternary operator it requires 3 operands.
These operands should be one of the following.

Literals e.g., 15, 20.0, true


Variables e.g., a, bonus, marks
Expressions e.g., 17 / 2, a + bonus, marks * 3
Operators In Java

The data type of operands is also important for operations. For some operations
like addition and subtraction, only numeric data types are supported and for
some operations like logical AND, only boolean data types are supported. The
details of the operators and the corresponding data types are mentioned in those
sections.
Java supports the following operator groups.

Operator Group Usage Examples

Java Arithmetic Operators Used in mathematical expressions + - * / -- ++

Java Bitwise Operators act upon the individual bits of their operands ~ & | >> << >>>=

Relational Operators In Java determines the relationship that one operand has to == != > < >= <=
the other
Boolean Logical Operators In are used only on boolean operands & | ^ && &= ^=
Java
Assignment Operator In Java is the single equal sign ('=') =

Ternary Operator In Java is used as if then else statement ?:


Java Arithmetic Operators

● Arithmetic Operators help in performing the algebra operations like addition,


subtraction, multiplication and division.

● The list of all supported Arithmetic Operators In Java are :

Arithmetic Operators Result

+ Addition (also unary plus)

- Subtraction (also unary minus)

* Multiplication

/ Division

% Modulus
A

++ Increment

+= Addition assignment

-= Subtraction assignment

*= Multiplication assignment

/= Division assignment

%= Modulus assignment

-- Decrement
Basic Arithmetic Operators In Java

● Basic Arithmetic Operators are sub group of Java Arithmetic Operators which
include only addition, subtraction, multiplication and division.
● Basic Arithmetic Operators In Java With Example Program.
class BasicAlgebra{
public static void main(String arg[]){
int a = 3 + 4;
int b = a * 4;
int c = b - a;
int d = b / 2;

System.out.println("a = " + a); OUTPUT


System.out.println("b = " + b);
System.out.println("c = " + c); a=7
System.out.println("d = " + d); b = 28
} c = 21
} d = 14
DESCRIPTION

In this example, 3 + 4 is assigned to a which will be 7,


a * 4 is assigned to b which will be 7 * 4 = 28,
b - a is assigned to c which will be 28 - 7 = 21,
b / 2 is assigned to d which will be 28 / 2 = 14
As we can see here, the operands could be literals (e.g., 3, 4), variables (e.g., a,
b) or expressions.
Increment And Decrement Operators In Java

Increment Operator increases its operand by 1. The Decrement Operator


decreases its operand by 1. Instead of x = x + 1; we could do x++;

Increment And Decrement Operators can be used both postfix (x++) and prefix
(++x). In the postfix form it is used and then incremented, where as in prefix form
it is incremented and then used.

int x = 42;
int y = ++x; // same as x = x + 1; followed by int y = x;
System.out.println("x = " + x + " y = " + y);
Pre and Post Increment

The above code prints x = 43 y = 43 where as the below code prints x = 43 y =


42

int x = 42;
int y = x++; // same as int y = x; followed by x = x + 1;
System.out.println("x = " + x + " y = " + y);
Pre and Post Increment CODE

aclass PreAndPostIncrement
{
public static void main(String arg[])
{
int a = 5;
int b = 2;
int c;
int d;
c = ++b; // LINE A
d = a++; // LINE B
c++; // LINE C
System.out.println("a = " + a + " b = " + b + " c = " + c + " d = " + d);

}
}

OUTPUT

a=6b=3c=4d=5
DESCRIPTION

Here a and b are declared as integers and they are assigned to 5 and 2
respectively.
In LINE A, we have prefix increment operator i.e. ++ before the operand b i.e. (
++b ). So the value of b is first incremented from 2 to 3 and then assigned to c.
Hence c becomes 3.
In LINE B, where we have postfix increment operator i.e. ++ after the operand a
i.e. ( a++ ), the value of a is first assigned to d, so d becomes 5. Later a is
incremented from 5 to 6.
In LINE C, c is incremented, so it goes from 3 to 4. Here there is no difference
whether we use postfix ( c++ ) or prefix ( ++c ) increment since we are not
assigning it or using it as part of some other expression.
Modulus Operator In Java

● Java has one important arithmetical operator you may not be familiar with, %,
also known as the modulus operator.
● The modulus operator, % returns the remainder of a division operation. e.g.,
15 % 4 = 3, 7 % 3 = 1, 5 % 5 = 0
Find Modulus

● As shown above, when we divide 17 (dividend) with 3 (divisor) then the


quotient is 5 and the modulus (or remainder) is 2.
● The Modulus Operator allows operation for both floating point types as well
as integer types.
class FindModulus
{
public static void main(String arg[])
{
int x = 32;
double y = 36.75;

System.out.println("x mod 10 = " + x % 10); OUTPUT


System.out.println("y mod 10 = " + y % 10);
x mod 10 = 2
} y mod 10 = 6.75
}
DESCRIPTION

When 32 is divided by 10, the quotient will be 3 and the modulus (or remainder)
will be 2. Similarly when 36.75 is divided by 10, the quotient will again be 3,
where as the modulus will be 6.75.
Arithmetic Compound Assignment Operators In Java

● Arithmetic Compound Assignment Operators In Java are used to combine an


arithmetic operation with an assignment operation. e.g., marks += 5; instead
of marks = marks + 5; Compound assignment operators provide a shorter
syntax for assigning the result of an arithmetic operator.

● If the we want to multiply a variable score by 3 and assign it to the same


variable score, we could use score *= 3; instead of using score = score * 3;
The general syntax of the compound assignment operators is
Arithmetic Compound Assignment Operators In Java

var op= expression;

Compound assignment is supported for addition, subtraction, multiplication,


division and modulus and the corresponding operators respectively are +=, -=,
*=, /=, %=

Compound assignment operators are faster than performing the operation and
then assigning. i.e. doing score *= 3; is faster than score = score * 3;
Compound Assignment Operators

aclass CompoundAssignments{
public static void main(String arg[]){
int x = 5;
int y = 2;
int z = 3;

x += 6; // LINE A
y *= 8; // LINE B
z += y * x; // LINE C
z %= 7; // LINE D

System.out.println("x = " + x);


System.out.println("y = " + y); OUTPUT
System.out.println("z = " + z);
x = 11
} y = 16
} z=4
DESCRIPTION

Here, we have declared three variables x, y and z and initialized them.


In LINE A, 6 is added to previous x value, which is 5 and assigned to x again. So
x becomes 11 (= 5 + 6).
In LINE B, the value of y is changed to 16 (= 8 * 2) from 2.
In LINE C, the y * x (= 16 * 11 = 176) is added to z and assigned to z again. So z
changes from 3 to 179 (= 176 + 3).
In LINE D, the value of z % 7 is assigned to z, so z becomes 4 (= 179 % 7).
Java Operator Precedence And Associativity

About Operator Precedence In Java :


Operator precedence plays an important role if there are multiple operators
involved in an expression.
int a = 7 * 3 + 24 / 3 - 5;

As shown above, if an expression contains multiple operators then the


expression is evaluated according to the precedence. In java * and / have more
precedence (or priority) compared to + and -. So first 7 * 3 and 24 / 3 is evaluated
and then the results are added.
// a = 7 * 3 + 24 / 3 - 5;
// a = 21 + 8 - 5
// a = 24
Java Operator Precedence And Associativity

● Although Java can evaluate using its precedence table, it is suggested to use
parentheses ( ) to avoid any confusion.
int a = 7 * 3 + 24 / 3 - 5; // Creates confusion - Not suggested.
int a = (7 * 3) + (24 / 3) - 5; // More clear to the user. - Suggested.

● Since parentheses have highest priority they will be evaluated first. Also note
that parentheses does not slow down the evaluation. Precedence table
showing all the operators supported in Java.
Java Operator Precedence And Associativity

Highest
++ (postfix) -- (postfix)
++ (prefix) -- (prefix) ~ ! + (unary) - (type-ca
(unary st)
)
* / %
+ -
>> >>> <
<
> >= < < instance
= of
== !=
Java Operator Precedence And Associativity

&
^
|
&&
||
?:
= op=(compoundassig
nment)
Lowest
Temperature Conversion Program In Java

● Learn Temperature Conversion Program In Java This program converts the


temperature in Fahrenheit to Celsius. The formula used is C = 5.0 * (F - 32.0)
/ 9.0 .

class TemperatureConversion
{
public static void main(String arg[])
{
double fahrenheit = 98.4;

double celsius = ( 5.0 * (fahrenheit - 32.0) ) / 9.0;

System.out.println(fahrenheit + " F is same as " + celsius + " C."); OUTPUT

} 98.4 F is same as
} 36.888888888888886 C.
DESCRIPTION

● Here we have declared a variable fahrenheit and initialized to 98.4. Then we


are using the formula to convert from fahrenheit to celsius. And finally we are
printing the result.
THANK YOU
Relational Operators
Question :01

What will be the output of the following program?

public class Relation {


public static void main(String args[]) {
int a = 10; A. true
int b = 15; B. false
a++; C. Compilation Error
b--; D. Runtime Error
int c = b % a;
System.out.println(c >= b);
}
}

B. false
For above question correct explanation is given below.
Question :02

What will be the values of var_a, var_b, var_c? After execution of the program.
public class ValuesAre {
public static void main(String args[]) { A. 21, 19, 21
int var_a = 20, var_b = 20, var_c = 20; B. 21, 19, 22
var_c += var_a++; C. var_a=21
var_c -= --var_b; var_b=19
System.out.print("var_a="); var_c=21
System.out.println(+var_a); D. var_a=21
System.out.print("var_b="); var_b=19
System.out.println(+var_b); var_c=22
System.out.print("var_c="); E. Some other values
System.out.println(+var_c); F. Compilation Error or Runtime Error
}
}
C. var_a=21
var_b=19
var_c=21
For above question correct explanation is given below.

c=20+20=41 but a=21 and c=40-19=21 so a=21 b=19 c=21


Question :03

What will be the output of the following program.


class Addition
{
public static void main(String s[]) A. a = 13
{ a = -3
int a = 4; B. a = 33
a -= 10; a = 163
a = -a; C. a = 33
a = 7 + a; a = -3
System.out.println(" a = " + a ); D. Program does not compile
a %= a;
a=a*a-3;
System.out.println(" a = " + a );
} A. a = 13
} a = -3
For above question correct explanation is given below.

Answer is A.. Here we have the concept of Arithmetic Compound Assignment


operator. These operators are used to combine an arithmetic operation with an
assignment operation. For example : marks += 5 ; will be used instead of Marks
= marks + 5; The general syntax of the compound assignment operators is var
op= expression; Coming to the program, initially we have initialized and declared
variable 'a' by assigning value 4 to it. Next step a -= 10 leads to a = -10+4 = -6.
Now this -6 value stored in a. Next step a = -a leads to a = -(-6) = 6. Now this
result stored in a. In final step a = 7+a = 7+6 = 13 and the result stored in a and
print method prints the a value to 13. In the next step a %= a leads to a = 13 %
13 = 0 now the result stored in a. In the next step, a = a * a - 3 = 0*0-3 = -3 will be
stored and print method will prints the value -3. Final output will be a = 13 and
a = -3.
Question :04

How should be the lines M, N, O and P ordered such that x is 11, y is 16 and z is
25 at the end of the program.
class CompoundAssignments
{
public static void main(String arg[]) A. M, N, O, P
{ B. P, O, N, M
int x = 5; C. N, O, P, M
int y = 2; D. M, P, O, N
int z = 3;

x += 6; // LINE M
y *= 8; // LINE N
z += y * x; // LINE O
z %= 7; // LINE P
}
} D. M, P, O, N
For above question correct explanation is given below.

Ans is D.. Here we got the concept of Arithmetic Compound Assignment Operators. This
operators are used to combine the Arithmetic operation to Assignment operation. For
example : We will write as Marks += 6; instead of Marks = +6; Compound assignment
operators are faster than performing the operation and then assigning. Coming to the
program, Here we have declared and initialised three variables x,y,z. In Line M , 6 is added
to the previous value of x which is 5, and assigned to x again. So x becomes 11 (=5+6). y
and z values remains the same. So x = 11, y = 2, z = 3 In Line P, z%7 is assigned to z, So
that z= 3%7, then z=3. so now x = 11, y = 2, z = 3. Now Line O, z+(y*x) is added and
assigned to z again. so that , z = z+(y*x) z= 3+(2*11); z= 25 . Now x = 11 , y = 2, z = 25 In
Line N, The value of y is changed to 16. because y *= 8 so that previous value of y is
multiplied with 8. i.e., y = 8*2= 16 Finally x = 11, y = 16 , and z = 25 condition satisfies by
executing in an sequential order of M, P , O , N Lines. If we go in other sequence of lines
the values of x,y,z changes.
Question :05

Choose the correct statement.

A. Both a >= b and a => b compares that a is greater than or equal to b.


B. = is an assignment operator where as == is a relational operator.
C. a == b is different from b == a
D. a > b is different from b < a

B. = is an assignment operator where as == is a


relational operator.
For above question correct explanation is given below.

A: To compare two values relational operators must be used. To check whether a


is greater than or equal to b the operator >= must be used. It cannot be replaced
by => since it causes syntax error and always ">" or "<" must be before "=" but
not viceversa.
B: = operator assigns the value on RHS to variable in LHS whereas == compares
whether LHS and RHS are equal or not.
C: a == b is same as b == a because a equal to b is same as b equal to a.
D: a > b is same as b < a
Question :06

What will be the output of the following program?

public class Test { A. false


public static void main(String args[]) { true
int a = 10; B. true
int b = a - 5; false
System.out.println(a <= b); C. false
System.out.println(a > b); false
} D. true
} true
E . Compilation Error or Runtime Error

A. false
true
For above question correct explanation is given below.
THANK YOU
Arithmetic Operators
Increment
Decrement
Compound
Assignment Output
Question :01

What will be the output of the following program?

class Addition
{ A. Program does not compile
public static void main(String s[]) B. a = 255
{ C. a = 253
int a = 4; D. a = 286
a++;
a += a;
--a;
a = 7 + a;
a *= a;
a -= 3;

System.out.println(" a = " + a );
}
} C. a = 253
For above question correct explanation is given below.

Execution of program starts from main. Inside main an integer variable a is declared and
initialized to 4.
a++ increments a to 5. This new value is reflected when a is used next time.
a += a -> a = a + a -> a = 5 + 5 = 10
--a decrements a to 9.
a = 7 + a = 7 + 9 = 16
a *= a -> a = a * a = 16 * 16 = 256
a -= 3 -> a = a - 3 = 256 - 3 = 253
The value of a is printed using the display statement. So output is a = 253.
Question :02

What will be the output of the following program?

class Operators1
{
public static void main(String[] args)
{ A. sum = 265
int a = 34; B. sum = 263
int b = 21; C. sum = 264
int c = a++ + ++b; D. Compilation Error
int d = --a + --b + c--;
int e = a + +b + +c + d--;
int f = -a + b-- + -c - d++;
int sum = a + b + c + d + e + f;
System.out.println("sum = " + sum);
}
} B. sum = 263
For above question correct explanation is given below.

ans is B there is no compilation error because we did not taking any arguments as inputs

Ans is B: sum is 263, here,, a + +b is represent as a+(+b).


Question :03

What will be the output of the following program?


class IncDec{
public static void main(String s[]){ A. a = 2
int a = 1; b = 3c = 4
int b = 2; d=1
int c; B. a = 2
int d; b=3
c = ++b; c=4
d = a++; d=1
c++; C. Program does not compile.
System.out.println("a = " + a); D. a = 1
System.out.print("b = " + b); b=2
System.out.println("c = " + c); c=4
System.out.print("d = " + d); d=2 A. a = 2
} b = 3c = 4
} d=1
For above question correct explanation is given below.

Execution of program starts from main. Four integer variables a, b, c, d are


declared among which a, b are initialized to 1, 2 respectively. Variable c is
assigned to ++b which is ++2 = 3. Now value of both c, b becomes 3 (since pre
increment). Variable d is assigned to a++ which is 1++ = 2. Now value of d
becomes 1 and a becomes 2. c++ performs increment but value is reflected for
next usage of c(since post increment). The four display statements print the
values as follows:
a=2
b = 3 c = 4 (next usage after increment of c is here in display statement)
d=1
Observe that for printing a and c values println is used, where as for b and d only
print is used.
Question :04

What will be the output of the following program?

class Modulus
{
A. x mod 10 = 2y mod 10 = 2.25
public static void main(String s[])
B. x mod 10 = 2
{
y mod 10 = 0
int x = 42;
C. Program does not compile since we can find
double y = 42.25;
modulus only for integers.
D. x mod 10 = 2
System.out.println("x mod 10 = " + x % 10 );
y mod 10 = 2.25
System.out.println("y mod 10 = " + y % 10 );
}
}

D. x mod 10 = 2
y mod 10 = 2.25
For above question correct explanation is given below.

Two variables x of type int and y of type double are declared and initialised. The
first display statement prints x % 10 i.e., 42 % 10 = 2.
The second display statement prints y % 10 i.e., 42.25 % 10 = 2.25.
Note: The modulus operator gives the remainder. That is when a % b is used it
gives the remainder when a is divided by b. Floating point modulus is allowed in
Java.
Question :05

What will be the output of the following program?

public class Precedence {


public static void main(String[] args) {
int x = 20;
int y = 10;
double z = x++ - y * 7 / --y + x * 10;
System.out.println(z);
}
}

A. 0.0
B. 20.0
C. 223.0
D. Some other output
E. Compilation Error or Runtime Error C. 223.0
For above question correct explanation is given below.

ans C post increment operator of x is 21 so 21 is taken as x value in the second


occurrence and using BDMS rule we will get and C
Question :06

What will be the output of the following program?

public class OperatorPrecedence {


public static void main(String[] args) {
int a = 7 * 3 + 24 / 3 - 5;
int b = (7 * 3) + (24 / 3) - 5;
System.out.print(a + ", " + b);
}
}

A. 24, 24
B. 33, 24
C. 33, 33
D. Compilation Error
E. Runtime Error
A. 24, 24
For above question correct explanation is given below.

A it is jst the normal precedence operation. a = 21 + 8 - 5 =24 b = 24 + 8 - = 24


Question :07

What will be the output of the following program?

public class Precedence {


public static void main(String[] args) {
int x = 20;
int y = 10;
double z = (x + y) * 7 + (--y + x);
System.out.println(z);
}
}

A. 120.0
B. 239.0
C. 240.0
D. Compilation Error or Runtime Error B. 239.0
For above question correct explanation is given below.

Answer is B.. Here we have the concept of Operator precedence. It plays an


important role when multiple operators involved in an expression. According to
operator precedence, paranthesis "( )" has tje highest precedence or priority, *
and / have the highest priority when compared to + and - . In the given program,
x and y initialized to 20 and 10 repectively. The given expression Double z =
(x+y)*7+(--y+x) expression contains paranthesis, so the inside ( ) will perform the
operation first i.e., (20+10)*7+(19+10) = (30)*7+(29) Now the expression contains
* and + operators. According to operator precedence, * has the highest priority
then +. So multiplication operation comes into play. Double z = (30)*7+29 =
210+29 Now finally + operation can be done. z = 239. Since z is double so the
result changes to 239.0
THANK YOU
Basic I/O Operations In Java
Using Console Class

● The Java.io.Console class provides methods to access the character-based


console device, if any, associated with the current Java virtual machine. The
Console class was added to java.io by JDK 6.
Using Console Class

● It is used to read from and write to the console, if one exists.


● Console is primarily a convenience class because most of its functionality is
available through System.in and System.out. However, its use can simplify some
types of console interactions, especially when reading strings from the console.
● Console supplies no constructors. Instead, a Console object is obtained by
calling System.console( ), which is shown here:

static Console console( )


Using Console Class

● If a console is available, then a reference to it is returned. Otherwise, null is


returned. A console will not be available in all cases. Thus, if null is returned, no
console I/O is possible.
● It provides methods to read text and password. If you read password using
Console class, it will not be displayed to the user.The java.io.Console class is
attached with system console internally.
Using Console Class

● Writer : Retrieves the unique PrintWriter object associated with this console.

public PrintWriter writer()


Returns: The printwriter associated with this console

● Reader : Retrieves the unique Reader object associated with this console.

public Reader reader()


Returns: The reader associated with this console
Using Console Class

● Format : Writes a formatted string to this console’s output stream using the
specified format string and arguments.
public Console format(String fmt, Object... args)
Parameters:
Returns:This console
Throws: IllegalFormatException
Using Console Class

● printf : A convenience method to write a formatted string to this console’s output


stream using the specified format string and arguments.
public Console printf(String format, Object... args)
Parameters:
Returns:This console
Throws:IllegalFormatException
Using Console Class

● ReadLine : Provides a formatted prompt, then reads a single line of text from the
console.
public String readLine(String fmt,Object... args)
Parameters:
Returns:
Throws:
IllegalFormatException
Using Console Class

● ReadPassword : Reads a password or passphrase from the console with


echoing disabled
public char[] readPassword()
Returns:
Throws:IOError
Using Console Class

● Flush : Flushes the console and forces any buffered output to be written
immediately .

public void flush()


Specified by: flush in interface Flushable
Using Console Class

import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
String str;
Console con = System.console();
if(con == null)
{
System.out.print("No console available");
return;
}
Using Console Class

str = con.readLine("Enter your name: ");


con.printf("Here is your name: %s\n", str);
System.out.println("Enter the password: ");
char[] ch=con.readPassword();
String pass = String.valueOf(ch);
System.out.println("Password is: " + pass);
}
}
Using Buffer Reader Class

Reads text from a character-input stream, buffering characters so as to provide

for the efficient reading of characters, arrays, and lines.


Using Buffer Reader Class

● The buffer size may be specified, or the default size may be used. The default
is large enough for most purposes.
● In general, each read request made of a Reader causes a corresponding read
request to be made of the underlying character or byte stream.
Using Buffer Reader Class

● It is therefore advisable to wrap a BufferedReader around any Reader whose


read() operations may be costly, such as FileReaders and
InputStreamReaders.
● Programs that use DataInputStreams for textual input can be localized by
replacing each DataInputStream with an appropriate BufferedReader.
Using Buffer Reader Class

Constructors:

● BufferedReader(Reader in) :
Creates a buffering character-input stream that uses a default-sized input
buffer.
● BufferedReader(Reader in, int sz) :
Creates a buffering character-input stream that uses an input buffer of the
specified size.
Using Buffer Reader Class

void close() :
Closes the stream and releases any system resources associated with
it.Once the stream has been closed, further read(), ready(), mark(), reset(), or
skip() invocations will throw an IOException. Closing a previously closed stream
has no effect.
public void close()
throws IOException
Throws:
IOException
Using Buffer Reader Class

void mark(int readAheadLimit) :


Marks the present position in the stream.Subsequent calls to
reset() will attempt to reposition the stream to this point.

public void mark(int readAheadLimit)


throws IOException
Parameters:
Throws:
Using Buffer Reader Class

boolean markSupported() :
Tells whether this stream supports the mark() operation, which it
does.

public boolean markSupported()


Returns:
Using Buffer Reader Class

int read() :
Reads a single character.

public int read()


throws IOException
Returns:
Throws:
IOException
Using Buffer Reader Class

int read(char[] cbuf, int off, int len) :


Reads characters into a portion of an array.

public int read()


throws IOException
Returns:
Throws:
Using Buffer Reader Class

String readLine() :
Reads a line of text.A line is considered to be terminated by any
one of a line feed (‘\n’), a carriage return (‘\r’), or a carriage return
followed immediately by a linefeed

public String readLine()


throws IOException
Returns:
Throws:
Using Buffer Reader Class

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[] args) throws IOException
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println(name);
}
}
Using Buffer Reader Class

class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);

int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
Using Scanner Class

This is probably the most preferred method to take input. The main purpose of
the Scanner class is to parse primitive types and strings using regular
expressions, however it is also can be used to read input from the user in the
command line.
Advantages
Convenient methods for parsing primitives (nextInt(), nextFloat(), …)
from the tokenized input
Regular expressions can be used to find tokens

Drawback
The The reading methods are not synchronized
Using Scanner Class

● To create an object of Scanner class, we usually pass the predefined object


System.in, which represents the standard input stream. We may pass an
object of class File if we want to read input from a file.
● To read numerical values of a certain data type XYZ, the function to use is
nextXYZ(). For example, to read a value of type short, we can use nextShort()
Using Scanner Class

● To read strings, we use nextLine().


● To read a single character, we use next().charAt(0). next() function returns the
next token/word in the input as a string and charAt(0) function returns the first
character in that string.
Using Scanner Class

import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string "+s);
int a = in.nextInt();
System.out.println("You entered integer "+a);
float b = in.nextFloat();
System.out.println("You entered float "+b);
}
}
Basic I/O Operations In Java –MCQ’s
QUESTION: 01

Which of these is used to perform all input & output operations in Java?

A. Streams
B. Variables
C. Classes
D. Methods

Answer: A
QUESTION: 02

Which of these is a type of stream in Java?

A. Integer stream
B. Short stream
C. Byte stream
D. Long stream

Answer: C
QUESTION: 03

Which of these classes are used by Byte streams for input and output operation?

A. InputStream
B. InputOutputStream
C. Reader
D. All of the mentioned

Answer: A
QUESTION: 04

Which of these classes are used by character streams for input and output
operations?
A. InputStream
B. Writer
C. ReadStream
D. InputOutputStream

Answer: B
QUESTION: 05

Which of the following statement is correct?


A. reverse() method reverses all characters.
B. reverseall() method reverses all characters.
C. replace() method replaces first occurrence of a character in invoking string with
another character.
D. replace() method replaces last occurrence of a character in invoking string with
another character.

Answer: A
QUESTION: 06

The …………………… package contains a large number of stream classes that provide
capabilities for processing all types of data.
A. java.awt
B. java.io
C. java.util
D. java.net

Answer: A
QUESTION: 07

State whether the following statements about the stream in Java.


i) The two basic streams used are the input and the output streams.
ii) Filters are used to read data from one stream and write it to another stream.
A. True, True
B. True, False
C. False, True
D. False, False

Answer: A
QUESTION: 08

The ……………………… class provides the capacity to read primitive data types from an
input stream.
A. pushbackInputStream
B. DataInputStream
C. BufferedInputStream
D. PipeInputStream

Answer: B
QUESTION: 09

……………….. streams provide functionally for threads to communicate and exchange


data between them.
A. Object
B. Piped
C. Pushback
D. Filtered

Answer: B
QUESTION: 10

Combining two or more input streams into a single input stream can be
achieved using the ………………. class.
A. SequenceOutputStream
B. BufferedInputStream
C. BufferedOutputStream
D. SequenceInputStream

Answer: D
QUESTION: 11

Which of these class is not a member class of java.io package?


A. String
B. StringReader
C. Writer
D. File

Answer: A
QUESTION: 12

Which of these interface is not a member of java.io package?


A. DataInput
B. ObjectInput
C. ObjectFilter
D. FileFilter

Answer: C
QUESTION: 13

What is the output of this program?

import java.io.*;
class files {
public static void main(String args[])
{
File obj = new File("/java/system");
System.out.print(obj.getName());
}
}

A. java
B. system
C. java/system Answer: B
D. /java/system
QUESTION: 14

What is the output of this program? Note: file is made in c drive.

import java.io.*;
class files
{
public static void main(String args[])
{
File obj = new File("/java/system");
System.out.print(obj.getAbsolutePath());
}
}

A. Java
B. System
C. java/system Answer: D
D. \java\system
QUESTION: 15

What is the output of this program? Note: file is made in c drive.

import java.io.*;
class files {
public static void main(String args[])
{
File obj = new File("/java/system");
System.out.print(obj.getParent());
System.out.print(" " + obj.isFile());
}
}

A. java true
B. java false
C. \java false Answer: C
D. \java true
QUESTION: 16

Which of these class is used to read and write bytes in a file?


A. FileReader
B. FileWriter
C. FileInputStream
D. InputStreamReader

Answer: C
QUESTION: 17

Which of these method of InputStream is used to read integer representation of


next available byte input?
A. read()
B. scanf()
C. get()
D. getInteger()

Answer: A
QUESTION: 18

Which of these data type is returned by every method of OutputStream?

A. Int
B. Float
C. Byte
D. none of the mentioned

Answer: D
QUESTION: 19

What is the output of this program? Note: inputoutput.java is stored in the disk

import java.io.*;
class filesinputoutput {
public static void main(String args[])
{
InputStream obj = new FileInputStream("inputoutput.java");
System.out.print(obj.available());
}
}

A. True
B. False
C. prints number of bytes in file Answer: C
D. prints number of characters in the file
QUESTION: 20

Which of these stream contains the classes which can work on character stream?
A. InputStream
B. OutputStream
C. Character Stream
D. All of the mentioned

Answer: C
QUESTION: 21

Which of these classes can return more than one character to be returned to input
stream?
A. BufferedReader
B. Bufferedwriter
C. PushbachReader
D. CharArrayReader

Answer: C
QUESTION: 22

Predict the output of following Java Programs

class Test {
protected int x, y;
}
class Main {
public static void main(String args[]) {
Test t = new Test();
System.out.println(t.x + " " + t.y);
}
}

A. 0.0
B. 0.1
C. 0.2 Answer: A
D. 0.4
QUESTION: 23

Predict the output of following Java Programs

class Test {
public static void main(String[] args) {
for(int i = 0; 1; i++) {
System.out.println("Hello");
break;
}
}
}

A. Hello
B. Hello 1
C. Hello 10 Answer: D
D. Compiler Error
QUESTION: 24

Predict the output of following Java Programs

class Test {
public static void main(String[] args) {
for(int i = 0; true; i++) {
System.out.println("Hello");
break;
}
}
}

A. Hello
B. Hello True
C. True true Answer: A
D. True Hello
QUESTION: 25

Predict the output of following Java Programs

class Main {
public static void main(String args[]) {
System.out.println(fun());
}
int fun() {
return 20;
}
}

A. Compiler Error
B. 20
C. 30 Answer: A
D. 00
QUESTION: 26

Predict the output of following Java Programs

class Main {
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
return 20;
}
}

A. 20
B. 30
C. 40 Answer: A
D. 0
QUESTION: 27

Predict the output of following Java Programs

class Test {
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
static int x= 0;
return ++x;
}
}

A. Compiler Error
B. 0
C. 100 Answer: A
D. 01
QUESTION: 28

Predict the output of following Java Programs

class Test {
private static int x;
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
return ++x;
}
}

A. 1

Answer:
QUESTION: 29

Predict the output of following Java Programs

class Test {
int x = 10;
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.x);
}
}

A. 1
B. 10
C. 100 Answer: B
D. Compiler Error
QUESTION: 30

Predict the output of following Java Programs

class Test {
int y = 2;
int x = y+2;
public static void main(String[] args) {
Test m = new Test();
System.out.println("x = " + m.x + ", y = " + m.y);
}
}

A. 1
B. 2
C. 3 Answer: A
D. 4
QUESTION: 31

What happen when a member is initialized in class declaration and constructor


both? Consider the following program.

public class Test {


int x = 2;
Test(int i) { x = i; }
public static void main(String[] args) {
Test t = new Test(5);
System.out.println("x = " + t.x);
}
}
A. 1

Answer:
QUESTION: 32

Consider the following program.

class Test1 {
Test1(int x) {
System.out.println("Constructor called " + x);
} A. 1
}
// This class contains an instance of Test1
class Test2 {
Test1 t1 = new Test1(10);
Test2(int i) { t1 = new Test1(i); }
public static void main(String[] args) {
Test2 t2 = new Test2(5);
}
} Answer:
QUESTION: 33

What is the output of this program?


import java.io.*;
public class filesinputoutput {
public static void main(String[] args) {
String obj = "abc";
byte b[] = obj.getBytes();
ByteArrayInputStream obj1 = new ByteArrayInputStream(b);
for (int i = 0; i < 2; ++ i) {
int c;
while ((c = obj1.read()) != -1) {
if(i == 0) {
System.out.print((char)c);
}
}}

A. Abc
Answer: A
B. ABC
C. Ab
D. AB
QUESTION: 34

A stream is a sequence of data.In Java a stream is composed of?


A. Bytes
B. Bits
C. Both A & B
D. None of the above

Answer: A
QUESTION: 35

Which stream does Java application uses to read data from a source, it may be a
file, an array, peripheral device or socket?
A. InputStream
B. OutputStream
C. Input/OutputStream
D. None of the above

Answer: A
QUESTION: 36

These commonly used methods of 


1) public abstract int read()throws IOException
2) public int available()throws IOException
3) public void close()throws IOException

A) OutputStream class
B) InputStream class
C) Input/OutputStream class
D) None of the above Answer: B
QUESTION: 37

Which is used an internal buffer, It adds more efficiency than to write data directly
into a stream. So, it makes the performance fast?
A. BufferedOutputStream
B. ByteArrayOutputStream
C. BufferedInputStream
D. ByteArrayInputStream

Answer: A
QUESTION: 38

Which are the ways to read data from the keyboard?


A. InputStreamReader
B. Console
C. Scanner
D. DataInputStream
E. All Mentioned above

Answer: E
QUESTION: 39

Which class can be used to read data line by line by readLine() method?
A. BufferedReader
B. InputStreamReader
C. DataInputStream
D. None of the above

Answer: A
QUESTION: 40

Which is Commonly used Methods of ByteArrayOutputStream class?


A. ByteArrayOutputStream()
B. ByteArrayOutputStream(int size)
C. public synchronized void writeTo(OutputStream out) throws IOException
D. Both A & B

Answer: C
Control statements
What you’ll learn

● Introduction to control statements


● Types
● Decision-making statements and its types
● Jump statements and its types
● Loops and its types
● Code snippets
● Gaming scenario
Through constructor
Introduction to control statements

● controls the flow of a program


● determines whether the other statements will be executed or not
● Types:
1) Decision making statements
2) Jump statements
3) Loops
Through constructor
Decision making statements

● Evaluates the expression


● Controls the flow of code based on the condition result
● Two types:
1) if
2) Switch
if statement

● Evaluates a condition
● Controls based on the condition result
● Either true or false
● Four types:
1) if
2) if-else
3) else-if
4) nested if
if statement

● Enables to enter the block of code only if condition evaluates to true


● Syntax:

if(<condition>) {

//block of code

}
if statement - Example

public class Numerics{


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
if-else statement

● The else block is executed if the condition of the if-block is evaluated as false
● Syntax:
if(<condition>) {
//block of code
}
else{
//block of code
}
if-else statement - Example
public class Numerics{
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
}else {
System.out.println("x + y is greater than 20"); }
}
else-if statement

● Contains the if-statement followed by multiple else-if statements


● Also define an else statement at the end of the chain
● Syntax:
if(<condition>) {
//block of code
}
else if{
//block of code
}
else{
//block of code
}
else-if statement - Example
public class Language{
public static void main(String[] args) {
String lang = "Java";
if(lang == "Python") {
System.out.println("language is python");
}else if (lang == "C++") {
System.out.println("lang is C++");
}else if(lang == "Java") {
System.out.println("lang is Java");
}else {
System.out.println(lang); }
}}
Nested-if statement

● if statement contains multiple if-else statements as a separate block of code.


● Syntax:
if(<condition>) {
if(<condition>) {
//block of code
} }
else if{
//block of code
}
else{
//block of code }
Nested if statement - Example

public class Language{


public static void main(String[] args) {
String lang = "Java";
if(lang == "HLL & IL") {
if(lang == “python”)
System.out.println("language is python");
}else if (lang == "C++") {
System.out.println("lang is C++");
}else if(lang == "Java") {
System.out.println("lang is Java");
}else {
System.out.println(lang); }

}}
Switch statement

● Checks the variable for the range of values defined for multiple cases
● Syntax:
switch <variable>
{
Case <option 1>:
//block of statements
Case <option n>:
//block of statements
Default:
//block of statements }
Jump statements

● Transfer the execution control to the other part of the program


● Two types:
1) break
2) continue
break

● breaks the current flow of the program


● transfers the control to the next statement outside the current flow.
● breaks the loop and switch statement - forceful terminations
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
} }
continue

● skips the specific part of the loop


● jumps to the next iteration of the loop immediately
● forceful iterations of the loop
for(int i = 0; i<= 2; i++) {
for(int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
} } }
Loops in Java

Executes a set of instructions/functions repeatedly when some conditions


become true. There are three types of loops in Java.

● for loop
● while loop
● do-while loop
For Loops

Iterates a part of the program several times if the number of iteration


is fixed.

● Simple For Loop


● Nested for loop
● For-each or Enhanced For Loop
● Labeled For Loop
Simple For Loop

Syntax:
for(Initialization; Condition; Increment/Decrement)
{
Statements;
}
For Loop

INITIALIZATION

FALSE
CONDITION

TRUE

STATEMENT

TERMINATE THE
INCR/DECR
LOOP
For Loop

class Main {
public static void main(String[] args)
i=0 i<3 o/p i++
{
0 true 0 1
for(int i = 0; i < 3; i++) {
System.out.println(i); 1 true 1 2
} 2 true 2 3
}
3 False - -
}
Example

class Main {
public static void main(String[] args) {
for(int i = 0; i < 3; i++) {
System.out.println(i);
}
System.out.println(i);
}
NOT WORKING, WHY
} ?
Example

class Main {
public static void main(String[] args) {
int i;
for(int i = 0; i < 3; i++) {
System.out.println(i);
}
}
}
NOT WORKING, WHY
?
Nested For Loop

public class Main {


public static void main(String[] args) {
for(int i = 1;i <= 3;i++) {
for(int j = 1;j <= 3;j++) {
System.out.println(i+" "+j);
}
}
}
}
Predict the output

public class Main {


public static void main(String[] args) {
for(int i = 1;i <= 5;i++) {
for(int j = 1;j <= i;j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Predict the output

public class Main {


public static void main(String[] args) {
int term = 6;
for(int i = 1;i <= term;i++) {
for(int j = term;j >= i;j--) {
System.out.print("* ");
}
System.out.println();
} } }
For Each Loop

public class Main {


public static void main(String[] args) {
int arr[] = {12,23,44,56,78};
for(int i:arr) {
System.out.println(i);
}
}
}
Infinite For Loop

public class Main {


public static void main(String[] args) {
for(;;) {
System.out.println("infinitive loop");
}
}
}
While Loop

● Iterates a part of the program several times.


● The number of iteration is not fixed
● Syntax:
while(condition)
{
//block of code

}
While Loop

CONDITION

TRUE FALSE

STATEMENT TERMINATE LOOP


Example

public class Main {


public static void main(String[] args) {
int i = 1;
while(i <= 10) {
System.out.println(i);
i++;
}
}
}
Infinite While Loop

If you pass true in the while loop, it will be infinitive while loop

while(true)
{
//code to be executed
}
Infinite While Loop

public class Main {


public static void main(String[] args) {
while(true) {
System.out.println("infinitive while loop");
}
}
}
do While Loop

● Iterates a part of the program several times.


● The number of iteration is not fixed and you must have to execute the loop
at least once.
● Syntax:
do
{
//block of code
}while(condition);
do While Loop

dO

STATEMENT

TRUE

CONDITION

FALSE
Example

public class Main {


public static void main(String[] args) {
int i = 1;
do{
System.out.println(i);
i++;
}while(i <= 10);
}
}
Infinite do While - Syntax

● If you pass true in the do-while loop, it will be infinitive do-while loop

do
{
//block of code
}while(true);
Infinite do While

public class Main {


public static void main(String[] args) {
do{
System.out.println("infinitive do while loop");
}while(true);
}
}
Predict the output

public class Main {


public static void main(String[] args) {
for(int i = 0; i <= 5; i++ )
{
System.out.println("i = " + i );
}
}
}
Predict the output

public class Main {


public static void main(String[] args) {
for(int i = 0; i < 5; i++)
{
System.out.println("Hello");
i++;
}
}
}
Predict the output
public class Main {
public static void main(String[] args) {
String s = "friends";
int x = 0;
do{
System.out.print(s.charAt(x));
x++ ;
}while (x < 2);
}
}
Predict the output

public class Main {


public static void main(String[] args) {
while(true);{
System.out.println("codemithra");
}
}
}
Predict the output

public class Main {


public static void main(String[] args) {
do{
System.out.println("Ethnus");
}while(false);
}
}
Through constructor
Code snippet

public class BreakForLoop {


public static void main(String arg[])
{
for(int i = 1; i <= 10; i++)
{
System.out.println("before breaking = " + i );
if(i == 6)
break;
System.out.println("after breaking = " + i );
}
System.out.println("for loop terminated.");
} }
Through constructor
Code snippet

public class BreakNestedForLoop {


public static void main(String[] args) {
for(int i=1;i<=3;i++) //1, 2 , 3
{
for(int j=1;j<=3;j++) //1 2
{
if(i==2&&j==2){
break; //forceful termination on inner for loop
}
System.out.println(i+" "+j); //11, 12, 13
//21,
//31, 32, 33
} } } }
Through constructor
Code snippet

public class BreakWhileLoop {


public static void main(String[] args) {
int a=1;
while(a<=10){
if(a==5)// 5==5
break; //forceful termination
System.out.print("\n\tStatement : " + a);//1 2
3 4
a++;//2
}
System.out.print("\n\tEnd of Program.");
}
}
Through constructor
Code snippet

public class BreakDoWhile {


public static void main(String[] args) {
int i=1;
do{
if(i==5) { //2==5, 3==5 4==5 5==5
i++; //6
break;
}
System.out.println(i); //1 2 3 4
i++; //2 3 4 5
}while(i<=10); //2<=10 , 3<=10, 4<=10, 5<=10
System.out.println(i);
} }
Through constructor
Code snippet

public class Continue1 {


public static void main(String[] args) {
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) { //4==4
continue; //forecful iteration
}
System.out.println(j); //01235 1235 235
}
}
}
Through constructor
Code snippet

class ContinueExample{
public static void main(String args[]) {
int first = 5, second = 20;
do {
if (first++ > --second) { //5>19, 6>18, 7>17, 8>16, 9>15, 10>15,
11>14, 12>13, 13>12
Continue ; } //14>11, 15>10
} while (first < 15);//6<15,7<15, 8<15, 9<15, 10<15, 11<15, 12<15,
13<15, 14<15,15<15
System.out.println("first = " + first + " and second = " + second);
}
}
Through constructor
Code snippet

public class ContinueNestedForLoop {


public static void main(String[] args) {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
continue;
}
System.out.println(i+" "+j);
}
}
}

}
Through constructor
Code snippet

public class ContinueWhileLoop {


public static void main(String[] args) {
int i = 1;
while(i<=10){ //1<=10 6<=10
if(i==5){ //5==5
i++; //6
continue;
}
System.out.println(i); //1 2 3 4 6...10
i++;//2 3 5
}

}}
Through constructor
Code snippet

public class ContinueDoWhileLoop {


public static void main(String[] args) {
int i=1;
do{
if(i==5){
i++; //6
continue;
}
System.out.println(i); //1 2 3 4 6
i++; //2 3 4 5 7
}while(i<=10); //3<=10
}
}
Pattern programming
What you’ll Learn

● Brief intro to pattern programming


● Benefits
● Approach
● Different patterns and programs
Pattern programming

● On the basis of different designs/patterns using characters/numbers or


combination of both
● Benefits
○ Enhances the logical thinking capabilities
● Prerequisites
○ Detailed understanding of control statements
Categories

● Star patterns
● Number patterns
● Character patterns
● Combination of numbers and characters

● Examples of the designs


○ Right triangle, left triangle, pyramid, inverted triangle, etc..
Approach

● Draw the given pattern in the blocks to have a clear representation


● Get the logic with respect to the pattern
● Imply in the code using the control statements
Rows ( i )

columns( j )
Code snippets
import java.util.Scanner;
public class Type1Program1 {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the row value");
int row = sc.nextInt();
System.out.println("Triangled stars");
for(int i = 1; i<=row; i++)
{
for(int j = 1; j<=i; j++)
System.out.print("*");
System.out.println();
} }
Code snippets
public class Type1Program2 {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the row value");
int num = sc.nextInt();
for(int i = 1; i<=num; i++)
{
for(int j= 1; j<=i;j++)
System.out.print(j);
System.out.println();
}
} }
Code snippets
public class Type1Program3 {
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
System.out.println("enter the row value: ");
int n=sc.nextInt();
for(int i=1;i<=n;i++)
{
char ch = 'A'; // extra variable initialization inside the
outer for loop to retain the initial value in every row.
for(int j=1;j<=i;j++)
System.out.print(ch++);//A
System.out.println();
}
} }
Code snippets
public class Type1Program4 {
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
System.out.println("enter the row value: ");
int n=sc.nextInt();
char ch='A';// extra variable initialization outside the outer
for loop to just print 'A' only once in the first row
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
System.out.print(ch++);
System.out.println();
}
} }
Code snippets
public class Type2Program1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the row value");
int num = sc.nextInt();
int space = num-1;
System.out.println("Triangled stars in the right side");
for(int i = 1; i<=num; i++) {
for(int k = 1; k<=space; k++)
System.out.print(" ");
for(int j = 1; j<=i; j++) {
System.out.print("*");
System.out.println();
space--; }
}
}
}
Code snippets
public class Type2Program2 { for(int j=1;j<=i;j++){
public static void main(String[] args){ if( ((i==1 )|| (i==n)) && ((j==1)
Scanner sc = new Scanner(System.in); || (j==n)) )
System.out.println("enter the row System.out.print("*");
value"); else if((j==1) || (j==i))
int n=sc.nextInt();
int ch1=1; System.out.print(ch2++);
char ch2 = 'A'; else
int space = n-1; System.out.print(ch1++);
for(int i=1;i<=n;i++){ }//end of j
for(int loop
k=1;k<=space;k++) space--;
System.out.println();
System.out.print(" "); }
}
}
}
Code snippets
public class Type3Program1 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("enter the row value");
int n=sc.nextInt();
int st=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=st;j++)
System.out.print("*");
System.out.println();
if(i<=n/2)
st++;
else
st--;
} } }
Code snippets
public class Type4Program1 {
public static void main(String[] args) {
int term = 6;
for(int i = 1;i <= term;i++) {
for(int j = term;j >= i;j--) {
System.out.print("*");
}
System.out.println();
}

}
Scanner class
What you’ll Learn

● Introduction to Java Scanner class


● Scanner Class constructors
● Scanner Class methods
Java Scanner

● Present in java.util package


● Breaks the input into tokens using a delimiter which is whitespace by
default.
● Scanner Class Declaration:

public final class Scanner

extends Object

implements Iterator<String>, Closeable


Java Scanner

● Provides nextXXX() methods to return the type of value such as


nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(),
nextFloat(), nextBoolean(), etc.

● To get a single character from the scanner, you can call


next().charAt(0) method which returns a single character.
Why Scanner

● 5-10% of the interviews will contain questions on this topic


● High demand in the market/IT industry
● To develop applications that would take the input from the user
Example

Real life example of Scanner is ATM Machine

● Cash Withdrawal
● Retrieve Mini-Statement
● Change Pin
● Based on Our Input
○ Select Option for Cash Withdrawal from Account
○ Enter the Amount
○ Enter the PIN
How to Get Java Scanner

● Scanner which reads input from the user

Scanner in = new Scanner(System.in);

● Scanner which parses the strings


Scanner in = new Scanner("Codemithra");
Scanner Class Constructors

Constructor Description
It constructs a new Scanner that produces
Scanner(File source) values scanned from the specified file.
It constructs a new Scanner that produces
Scanner(File source, String charsetName) values scanned from the specified file.
It constructs a new Scanner that produces
Scanner(InputStream source) values scanned from the specified input stream.
Scanner(InputStream source, String It constructs a new Scanner that produces
charsetName) values scanned from the specified input stream.
It constructs a new Scanner that produces
Scanner(Readable source) values scanned from the specified source.
Scanner Class Constructors

Constructor Description
It constructs a new Scanner that produces values
Scanner(String source) scanned from the specified string.
Scanner(ReadableByteChannel It constructs a new Scanner that produces values
source) scanned from the specified channel.
Scanner(ReadableByteChannel It constructs a new Scanner that produces values
source, String charsetName) scanned from the specified channel.
It constructs a new Scanner that produces values
Scanner(Path source) scanned from the specified file.
Scanner(Path source, String It constructs a new Scanner that produces values
charsetName) scanned from the specified file.
Important Methods of Scanner class

public String next() Returns the next token from the


scanner

public String nextLine() Moves the scanner position to the next


line and returns the value as a string

public int nextInt() Scans the next token as an int value

public float nextFloat() Scans the next token as a float value

public double nextDouble() Scans the next token as a double value


Scanner Class Methods

Return type Method Description


void close() It is used to close this scanner.
It is used to get the Pattern which the Scanner class is
pattern delimiter() currently using to match delimiters.
It is used to find a stream of match results that match
Stream findAll() the provided pattern string.
It is used to find the next occurrence of a pattern
constructed from the specified string, ignoring
String findInLine() delimiters.
It is used to find the next occurrence of a pattern
constructed from the specified string, ignoring
string findWithinHorizon() delimiters.
Example

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("------Welcome to Ethnus ATM-------");
System.out.println("Enter the amount to withdraw");
int amount = in.nextInt();
System.out.print("Enter the PIN: ");
int pin = in.nextInt();
System.out.println("Thanks for Using Ethnus ATM");
System.out.println("Amount you have withdrawn is:" + amount);
in.close(); } }
Scanner Class Methods

Return type Method Description


Returns true if this scanner has another token in its
boolean hasNext() input.
Checks if the next token in this scanner's input can be
interpreted as a BigDecimal using the
boolean hasNextBigDecimal() nextBigDecimal() method or not.
Checks if the next token in this scanner's input can be
interpreted as a BigDecimal using the
boolean hasNextBigInteger() nextBigDecimal() method or not.
Checks if the next token in this scanner's input can be
interpreted as a Boolean using the nextBoolean()
boolean hasNextBoolean() method or not.
Scanner Class Methods

Return type Method Description


Checks if the next token in this scanner's input can be
interpreted as a BigDecimal using the nextByte() method
boolean hasNextDouble() or not.

Checks if the next token in this scanner's input can be


boolean hasNextFloat() interpreted as a Float using the nextFloat() method or not.

Checks if the next token in this scanner's input can be


boolean hasNextInt() interpreted as an int using the nextInt() method or not.

Checks if the next token in this scanner's input can be


boolean hasNextLong() interpreted as a Long using the nextLong() method or not.
Scanner Class Methods

Return type Method Description


It is used to check if the next token in this scanner's input can
be interpreted as a Short using the nextShort() method or
boolean hasNextShort() not.
It is used to get the IOException last thrown by this Scanner's
IOException ioException() readable.

Locale locale() It is used to get a Locale of the Scanner class.


It is used to get the match result of the last scanning
MatchResult match() operation performed by this scanner.
It is used to get the next complete token from the scanner
String next() which is in use.
Scanner Class Method

Return type Method Description


BigDecimal nextBigDecimal() It scans the next token of the input as a BigDecimal.

BigInteger nextBigInteger() It scans the next token of the input as a BigInteger.


It scans the next token of the input into a boolean value and
boolean nextBoolean() returns that value.

byte nextByte() It scans the next token of the input as a byte.

double nextDouble() It scans the next token of the input as a double.


Scanner Class Method

Return type Method Description


float nextFloat() It scans the next token of the input as a float.

int nextInt() It scans the next token of the input as an Int.


It is used to get the input string that was skipped of the
String nextLine() Scanner object.

long nextLong() It scans the next token of the input as a long.

short nextShort() It scans the next token of the input as a short.


Scanner Class Method

Return type Method Description


int radix() It is used to get the default radix of the Scanner use.
It is used when remove operation is not supported by
void remove() this implementation of Iterator.

Scanner reset() It is used to reset the Scanner which is in use.


It skips input that matches the specified pattern, ignoring
Scanner skip() delimiters
It is used to get a stream of delimiter-separated tokens
Stream<String> tokens() from the Scanner object which is in use.
Scanner Class Method

Return type Method Description


It is used to get the string representation of Scanner
String toString() using.
It is used to set the delimiting pattern of the Scanner
Scanner useDelimiter() which is in use to the specified pattern.
It is used to sets this scanner's locale object to the
Scanner useLocale() specified locale.
It is used to set the default radix of the Scanner which is
Scanner useRadix() in use to the specified radix.
It is used to get the string representation of Scanner
String toString() using.
Example

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Example
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("--------Enter Your Details-------- ");
System.out.print("Enter your name: ");
String name = scan.next();
System.out.print("Enter your age: ");
int i = scan.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = scan.nextDouble();
System.out.println("Salary: " + d);
scan.close(); } }
Example
import java.util.*;
public class Main {
public static void main(String args[]) {
String str =
"Codemithra/is/a/learning/platform/";
Scanner scanner = new Scanner(str);
scanner.useDelimiter("/");
System.out.println("---Result---");
while(scanner.hasNext()) {
System.out.println(scanner.next());
}
System.out.println("Delimiter used: " +scanner.delimiter());
}
}
Through constructor
Gaming scenario!
Problem statement

Code a java program which will let the user and


computer play the “Rock,paper,scissors” game on
the console. Get the required input from the
users using the scanner class.Think, implement
the logics and conditions required to accomplish
the task using the combinations of
appropriate control statements.

Additional task

Announce the best winners from computer vs


user. Say, the user & computer plays 3 rounds of
game. The best winner is the one who has won
minimum of 2 rounds / all the 3 rounds.
Through constructor
Sample output

Note:
Also think about other combination
of choices to arrive at the optimized
game environment. And, enhance
the detailed notifications to the
users. Say, display information
about what defeats what, include
logic for draw match, notify the
same, etc..

The more you enhance the code,


more your logical thinking
Question: 01

Which of these are selection statements in


Java?

A. If

B. For

C. Continue

D. break
Question: 02

Which of these selection statements test


only for equality?
A. If

B. Switch

C. Both

D. None of the above


Question: 03

//Predict the output:


class Main {
public static void main(String args[]) {
A. 1
int var1 = 5;
B. 2
int var2 = 6;
C. 3
if ((var2 = 1) == var1)
D. 4
System.out.print(var2);
else
System.out.print(++var2);
} }
Question: 04

//Predict the output:


class Main { A. 1
public static void main(String args[]) {
int a = 4; 2
if (a <= 0) { A. 2
if (a == 0) {
System.out.println("1 "); 3
} else { A. 1
System.out.println("2 ");
} 3
} A. 3
System.out.println("3 ");
}
}
Question: 05

//Predict the output:


class Test {
public static void main(String[] args) {
boolean b = true;
A. Hello
if (b = false) {
System.out.println("HELLO"); B. Bye
} else {
C. Compilation Error
System.out.println("BYE");
} D. No output
}
}
Question: 06

//Predict the output:


class Main {
public static void main(String args[]) {
int sum = 0;
A. 5
for (int i = 0, j = 0; i < 5 & j < 5; ++i, j = i + 1)
sum += i; B. 6
System.out.println(sum);
C. 14
}
} D. Compilation error
Question: 07

//Predict the output:


class Main {
public static void main(String args[]) {
int x = 2;
A. 1,3,5,7
int y = 0;
for (; y < 10; ++y) { B. 2,4,6 8
if (y % x == 0)
C. 1,3,5,7,9
continue;
else if (y == 8) D. 1,2,3,4,5,6,7,8,9
break;
else
System.out.print(y + " ");
}
}
}
Question: 08

//Predict the output:


class Main {
public static void main(String args[]) {
int a = 5;
A. 5 10
int b = 10;
first: { B. 10 5
second: {
C. 5
third: {
if (a == b >> 1) D. 10
break second;
}
System.out.println(a);
}
System.out.println(b);
} }
Question: 09

class Main {
public static void main(String[ ] args) {
do
while (true)
A. HELLO
System.out.println("HELLO");
while (false); B. Compile Time Error
}
C. HELLO(infinitely)
}
D. NO OUTPUT
Question: 10

class Test {
public static void main(String[] args) {
do
System.out.println("FRIENDS");
A. Compile time error
while (true);
System.out.println("ENEMY"); B. FRIENDS
}
C. No output
}
D. ENEMY
Question: 11

class Test {
public static void main(String[] args) {
do {
System.out.print(1);
A. 1 2
do {
System.out.print(2); B. 2 1
} while (false);
C. 1
} while (false);
} D. 2
}
Question: 12

What is true about a break? A. Break stops the execution of entire


program
B. Break halts the execution and forces
the control out of the loop
C. Break forces the control out of the loop
and starts the execution of next
iteration
D. Break halts the execution of the loop
for certain time frame
Question: 13

public class Test {


public static void main(String[] args) {
for (int i = 0, String = “CFG "; i < 2; i++)
System.out.println("HELLO WORLD"); A. Hello World
} B. Compile Time Error
}
C. Hello World
D. Hello World, Hello World.
E. No Output
Question: 14

class Test {
public static void main(String[] args) {
int i = 0;
for (System.out.println("HI"); i < 1; i++)
A. HI HELLO PIE
System.out.println("HELLO PIE");
} B. NO OUTPUT
}
C. Compile Time Error
D. HELLO PIE
Question: 15

class Test {
public static void main(String[] args) {
for(int i=0;i<1;System.out.println("WELCOME"))
System.out.println("GREAT");
A. GREAT WELCOME
}
} B. No Output
C. Compile time error
D. GREAT WELCOME(Infinitely)
Question: 16

class Test {
public static void main(String[] args) {
boolean b = true;
if (b = false) {
A. Hello
System.out.println("HELLO");
} else { B. Bye
System.out.println("BYE");
C. Compilation Error
}
} D. No output
}
Question: 17

public class Main{


public static void main(String args[]){
int a=15;
int b=25;
if ((a<b) || (a=5)>15) A. Error
System.out.println(a); B. 15
else C. 25
System.out.println(b); D. No output
}
}
Question: 18

public class Main


{
public static void main(String args[]) {
int a=5,b=18;
if((a=3)==b) A. 3
{ B. 18
System.out.println(++a); C. 19
} D. 6
else
{
System.out.println(++b);
}
}
}
Question: 19

class Factorial
{
public static void main(String s[])
{
int number = 5; A. Factorial of 5: 1
B. Factorial of 5: 120
int factorial = 1; C. Compilation Errors
D. Factorial of 5: 625
for(int i = 2; i <= number; i++ )
{
factorial *= factorial;
}
System.out.println("Factorial of 5:” + factorial);
}
}
Question: 20

Which of the following statements is true?


1. for every 'if' there should be an 'else'.
2. for every 'else' there should be an 'if'.
3. 'if' block can exist without an 'else'.
4. 'if' condition can be used inside another 'if' A. Only 2, 3 and 4 are true.
condition. B. All of the statements are true.
C. Only 2 and 3 are true.
D. Only 3 is true.
Question: 21

public class Main


{
public static void main(String[] args) {
boolean male=false;
int age=30; A. Girl
if(male) B. Woman
if(age<20) C. Boy
System.out.println("Boy"); D. Man
else
System.out.println("Man");
else
if(age<20)
System.out.println("Girl");
else
Question: 22

public class Main


{
public static void main(String[] args) {
boolean male=false;
A. Congratulations
int marks=80; Distinction
if(marks>70) { A. Pass
Distinction
System.out.println("Distinction");
A. Distinction
System.out.println("Congratulations"); Congratulations
} A. Compilation Errors
else if(marks>35) {
System.out.println("Pass");
}
else {
System.out.println("Fail");
System.out.println("Better Luck Next Time");
Question: 23
public class Main {
public static void main(String[] args) {
int day=4; A. Thursday
switch(day) {
case 1: B. Compilation Errors
System.out.println("Monday"); C. Runtime Error
case 2:
System.out.println("Tuesday"); D. Thursday
case 3: Friday
System.out.println("Wednesday");
case 4: Weekend
System.out.println("Thursday");
case 5:
System.out.println("Friday");
default:
System.out.println("Weekend");
break;
}
}
}
Question: 24

Which of the following two types are


acceptable as expressions for the switch
statement? The expression in the below A. 1 and 3
example is expr.
switch(expr) B. 2 and 4
{
C. 3 and 5
default:
System.out.println("Hello"); D. 4 and 6
}
}
}

1. byte 2. long 3. char 4. float 5. double 6.


boolean
Question: 25

public class Main


{
public static void main(String[] args)
{ A. No output
if(1>2){ B. 1 is greater than 2
System.out.println("1 is greater than 2");
} C. 2 is greater than 1
}
} D. Runtime error
/ethnuscodemithra Ethnus /ethnus /code_mithra
Codemithra

https://learn.codemithra.com

codemithra@ethnus.com +91 7815 095 +91 9019 921


095 340
Control Statements
In Java
Control Statements In Java

● The control statements, as the name suggests controls the flow of the
program. Depending upon the state ( values of variables, user input etc ) the
appropriate code is executed. These help in executing or by passing certain
parts of the code, or executing them multiple times or skipping some lines of
code etc.,.

● These control statements in Java can be used together and they can be
nested in one other. A program might contain multiple control statements,
having them used in the same blocks of code or they can be nested. There is
no limitation on the usage of these statements. The control statements in java
are of following types :
Control Statements In Java

● Selection Statements In Java help in executing or by passing the code


blocks. The supported statements are : if-else and switch

● Iteration Statements Or Loops In Java help in executing a block multiple


times. The supported statements are : while, do-while and for

● Jump Statements In Java help in jumping or skipping certain parts of code.


The supported statements are : break, continue and return
Airport example
airport example

the above airport example, the following controls are used.

Whether to take the wheel chair or not

Doing baggage scan of multiple baggage or suit cases

Returning back, if the flight is full

Removing insecure items at security check

Going to the appropriate gate group and then to the gate


Selection Statements In Java

● Java supports two selection statements - if and switch. These statements


allow us to control the flow of the program. Depending upon the expressions
or values, the corresponding blocks/statements of code will be executed or by
passed.
The two statements are

● if statement is a conditional branch statement. This is a two way branch


statement. Depending upon the whether a condition is true or false, the
corresponding code is executed.

● switch statement is a multiway branch statement. Depending upon the


value used for switching, the corresponding code is executed.

● These two statements are very powerful and are used widely across any
application. They provide effective solutions for branching problems.
if Condition In Java

● if condition in Java is a conditional branch statement, which can be used to


route program execution through different paths.

● if condition in Java can be used to execute a block of code only when a


condition is true, if the condition is false we can execute a different block of
code.

if(condition)
{
statement1;
}
else
{
statement2;
}
Print PassFail Result

aclass PrintPassFail
{
public static void main(String arg[])
{
int marks = 62;
if(marks > 35) // LINE A
{
System.out.println("Pass"); // LINE B
}
else
{
System.out.println("Fail"); // LINE C
}
OUTPUT
}
} Pass
DESCRIPTION

Here marks are initialized to 62. Then the condition marks > 35 will become true,
so LINE B is executed which prints Pass. If the marks are only 20, instead of 62,
then the condition is false, causing LINE C to execute, printing Fail.
THINGS TO TRY

Try the below code.


int a = 10;
int b = 5;
if (a > b)
System.out.println("a is greater than b");
else
System.out.println("b is greate than a");

The output should be a is greater than b, since the value of a is greater than b.
Try the below code.
The output should be as
int a = 10; shown.
int b = 9; a is greater than b
if (a > b) I am not in if block
System.out.println("a is greater than b"); Only the first statement below
System.out.println("I am not in if block"); if condition comes into if
block.
THINGS TO TRY

● It is not necessary to have an else block for every if condition . An if can


exist without else. In this scenario if block is executed only if the condition is
true, otherwise nothing is executed.

● It is not necessary to put the code in flower brackets { }, if only one


statement needs to be executed. If there are more than one statement, then
we need to put them in flower brackets { }. This is valid even for else block.
But writing if-else conditions without flower brackets is not suggested as it
causes confusion, if the code is not formatted properly. Please refer
Expressions, Statement, Line & Block In Java to understand the difference
between expression, statement, line and blocks of code.
Which of the following statements is true.

1. for every 'if' there should be an 'else'.


2. for every 'else' there should be an 'if'.
3. 'if' block can exist without an 'else'.
4. 'if' condition can be used inside another 'if' condition.

A. Only 2, 3 and 4 are true.


B. All of the statements are true.
C. Only 2 and 3 are true.
D. Only 3 is true.

A.Only 2, 3 and 4 are true.


Nested if Statements In Java

● When a if condition is included in the if block of some other if condition then


those are called nested ifs.

● We can have as many nested ifs and it can go into many levels.
Classify Person

class ClassifyPerson System.out.println("Woman");


{ }
public static void main(String arg[]) }
{ else
int age = 35; {
char gender = 'F'; // M - Male, F - Female if( gender == 'M' ) // LINE B
{
if( age > 35 ) // outer if System.out.println("Boy");
{ }
if( gender == 'M' ) // LINE A else
{ {
System.out.println("Man"); System.out.println("Girl");
} }
else
{ }
OUTPUT
}
} Girl
DESCRIPTION

Here we have two variables age and gender. In the outer if the condition age >
35 is checked, if its true, the block starting with LINE A is executed. The inner if
condition present in LINE A checks for gender and prints Man or Woman. If age
is less than 35 then the else block starting with LINE B is executed. The if in LINE
B checks for gender and prints Boy or Girl.
THINGS TO TRY

● Add one more variable marks of type int to the above program and modify the
program such that it prints Intelligent when marks greater than or equal to 75,
otherwise it prints Dull. and If age greater than or equal to 35 and gender
equal to M it prints Man otherwise it prints Woman. Boy or Girl when age less
than 35.
● Examples:
● 1. when marks are 75, age is 35 and gender is F output should be Intelligent
Woman
● 2. marks are 40, age is 22 and gender is M output should be Dull Boy
if else if ladder In Java

● It is very common in programming to have more than two ways (or


branches).
● e.g., printing the grade of a student like "Distinction", "First Class", "Second
Class" and "Fail" instead of simply "Pass" or "Fail".
● In this case if-else-if ladder will be very useful.
if( condition1 ){
statement1; // BLOCK 1
}
else if( condition2 ){
statement2; // BLOCK 2
}
else if( condition3 ){
statement3; // BLOCK 3
}
else{
statement4; // BLOCK 4
}
Example:

● The above if conditions are executed top down. If the condition1 is true, only
statement1 is executed, the other statements - statement2 and statement3
will not be executed.
● If the condition1 is false and condition2 is true, then only statement2 is
executed. If condition1, condition2 are false but condition3 is true, then only
statement3 is executed. If all the conditions - condition1, condition2 and
condition3 are false, then statement4 is executed.
● Also note that when condition1 is true, irrespective of whether other
conditions are true or false, only statement1 will be executed. statement2 and
statement3 will not be executed.
Print Student Grade
class PrintStudentGrade{
public static void main(String arg[]){
int marks = 65;
if( marks > 75 ) // CONDITION A
{
System.out.println("Distinction"); // LINE A
}
else if( marks > 60 ) // CONDITION B
{
System.out.println("First Class"); // LINE B
}
else if( marks > 50 ) // CONDITION C
{
System.out.println("Second Class"); // LINE C
}
else{
System.out.println("Fail"); // LINE D
}
} OUTPUT
}
First Class
DESCRIPTION

Since the marks are 65, the CONDITION A will be false, so the CONDITION B in
the else is executed. Since CONDITION B is true, LINE B is executed printing
First Class.
THINGS TO TRY

● Change the marks to 75, 53 and 32 and see the output in each case.

● Try removing the else conditions and see the result with various values.

● Change the program to achieve the same functionality with out using the
else block.
switch Statement In Java

● if-else is a two way branch statement. if-else-if ladder is a multi-way branch


statement.
● switch provides a better multi-way branch than if-else-if ladder which executes
multiple branches depending on the values of an expression.

switch(expression)
{
case value1:
// statement1;
break;
case value2:
// statement2;
break;
default:
// statement3;
break;
}
switch Statement In Java

● The expression must be of type byte, short, int or char.

● From JDK7, expression as String is also supported.

● Each value provided in case should be a literal value and variables are not
allowed here.

● Duplicate case values are not allowed.

● The type of each value must be compatible with the expression.


switch Statement In Java

● The value of expression is evaluated and compared with each of the values in
case statements. Those are value1, value2. If the value matches with value1
then statement1 is executed, if it matches value2 then statement2 is
executed. If it matches none of the values, then the statement3 which is under
default section is executed.
● It is not necessary to have default statement for every switch. When value of
expression does not match any of the values and their is no default section,
then no statement is executed.
● It is necessary to put a break statement after every case block if we want to
stop the execution. If there is no break it continues to execute the other
statements present in the switch statement. This is called fall-through.
Print Direction

class PrintDirection{
public static void main(String arg[]){
char direction = 'S';
switch( direction ){
case 'E': System.out.println("East"); // LINE A
break;
case 'W': System.out.println("West"); // LINE B
break;
case 'S': System.out.println("South"); // LINE C
break;
case 'N': System.out.println("North"); // LINE D
break;
default: System.out.println("Unknown Direction"); // LINE E
break;
} OUTPUT
System.out.println("After switch"); // LINE F
} South
} After switch
DESCRIPTION

Since the value of direction is 'S', it is compared with various values 'E', 'W', 'N'
and 'S'. Since it matches 'S', LINE C is executed. If the direction was 'N' instead
of 'S', then LINE D is executed. If the direction was 'M', since it does not match
any of the values, the LINE E in the default section is executed.
THINGS TO TRY

● Remove the default section and initialize the direction to 'M'.


● Remove the break statement after LINE C. When you remove the break, the
control does not break after LINE C and executes LINE Dhence printing North
and then it breaks since it encounters break after LINE D. This is also called
fall-through.
● Try putting duplicate case values, by changing 'W' also to 'S'. case 'W' in
LINE B to case 'S'.
● Try putting ascii code of 'S' which is 83 instead of char 'S' i.e. case 83:
instead of case 'S':.
● Move the default block above and see that default need not be the last
case and can be present any where.
if else Vs switch Performance In Java

● Although if-else and switch are multi-way branch statements, they are not
completely same.

● switch can be used only for a specific value and can not be used for range
of values or for conditions involving multiple variables. e.g., for switch the
values should be 1 or 2 or 3 etc, when we use if we could use conditions like
greater than 1 and less than 15 etc.

● In switch we can execute multiple blocks for one value, when we remove
break statement. i.e. use fall-through. Writing the below program using if
statement is difficult will have duplicate code.
A

achar letter = 'C';


if(letter == 'A' || letter == 'E')
{
System.out.println("This is an vowel.");
System.out.println("This is an alphabet.");
}
else if(letter == 'B' || letter == 'C' || letter == 'D')
{
System.out.println("This is an alphabet.");
}
else if(letter == '@' || letter == '#')
{
System.out.println("This is a special character.");
}
Same code using switch statement.

achar letter = 'C';


switch(letter)
{
case 'A':
case 'E':
System.out.println("This is an vowel.");
// FALL - THROUGH, NO BREAK HERE
case 'B':
case 'C':
case 'D':
System.out.println("This is an alphabet.");
break;
case '@':
case '#':
System.out.println("This is a special character.");
break;
}
switch is faster and simpler than if in some cases as shown below

aif( direction == 'E' )


System.out.println("East");
else if( direction == 'W' )
System.out.println("West");
else if( direction == 'S' )
System.out.println("South");
else if( direction == 'N' )
System.out.println("North");
else
System.out.println("Unknown direction");
The above if-else-if ladder is slower and complex than equivalent switch as
shown below.
switch( direction )
{
case 'E':
System.out.println("East");
break;
case 'W':
System.out.println("West");
break;
case 'S':
System.out.println("South");
break;
case 'N':
System.out.println("North");
break;
default:
System.out.println("Unknown direction");
break;
}
Nested switch Statements In Java

Similar to if statement, switch statements can be nested as well.


class PrintSubjects{ System.out.println("Data case 3:
public static void main(String structures, Java, Computer switch( branch ) // LINE D{
arg[]){ Organization"); case 'C':
char branch = 'E'; // C - break; System.out.println("Operating
CSE, E - ECE, M - Mech case 'E': System, RDBMS");
int year = 2; System.out.println("Micro break;
switch( year ){ processors, Logic switching case 'E':
case 1: theory"); System.out.println("Fundamental
System.out.println("English, break; s of Logic Design,
Maths, Drawing"); case 'M': Microelectronics");
break; System.out.println("Drawing, break;
case 2: Manufacturing Machines"); case 'M':
switch( branch ) // LINE C{ break; System.out.println("Internal
case 'C': } Combustion Engines,
break; Mechanical Vibration");
break; }
OUTPUT
break;}}}
Micro processors, Logic switching theory
DESCRIPTION

This program prints the engineering subjects for a given branch and year.
Variable branch specifies the branch - 'C' for CSE, 'E' for ECE, 'M' for Mechanical
and the year specifies the year 1, 2, 3 or 4. We have used nested switch to print
the subjects.
For first year since every branch has same subjects, there is no inner switch. But
from second year there is an inner switch which prints, different subjects for
different branches. We have intentionally not included the subjects for fourth year
THINGS TO TRY

● Add the case for final year (year 4) and print the subjects in the final year.

● Support additional branch IT with branch code 'I'. This means we have to
include the case statements for this branch (case 'I':) in switch block at LINE
C for 2nd year and in switch block at LINE D for 3rd year.
Fall Through Switch Case Statements In Java

● It is not necessary for every case in the switch Statement In Java to have a
break.
● Some times we might have a situation where we have the same or similar
handling for multiple cases.
Print Alphabets Classification
class AlphabetsClassification{
public static void main(String arg[]){
char alphabet = 'A';
switch(alphabet){
case 'A':
System.out.println("The alphabet '" + alphabet + "' is in first four letters");// LINE A
case 'E':
case 'I':
case 'O':
case 'U': OUTPUT
System.out.println("The alphabet '" + alphabet + "' is an vowel");
break; The alphabet 'A' is in first four
case 'B': letters
case 'C': The alphabet 'A' is an vowel
case 'D':
System.out.println("The alphabet '" + alphabet + "' is in first four letters");
default:
System.out.println("The alphabet '" + alphabet + "' is a consonant");
} }}
DESCRIPTION

This program classifies a given alphabet and prints whether it is in the first four
letters and whether it is a vowel or a consonant. Here we can observe that we
are not using the break statement for every case statement. When there is no
break, the execution continues until it encounters a break or if it reaches the end
of the switch statement. That is the reason why when the alphabet is 'A', it prints
both The alphabet 'A' is in first four letters and The alphabet 'A' is an vowel. At
LINE A, it simply falls through to the next case.
Identify the incorrect statement in the following.

A. if is two way statement where as switch is multiway statement.


B. the expression passed to switch should be of type byte, short, int or char.
C. Every case in switch should contain break.
D. default can or can not be present in a switch statement.

C.Every case in switch should contain break.


Block Of Code In Java

● Block of code in Java allows grouping of two or more statements. We use


curly braces { } to denote a block of code in Java. Block of code in Java can
be used where ever we use a statement.

● Every block of code in Java starts with a open curly brace { and ends with
close curly brace }.

● There is no restriction on the number of blocks inside a block and the level
of nesting the blocks. i.e. Blocks can be nested and can be included inside
other blocks.
Block Of Code In Java

● Block of code in Java is commonly used in if, for and while statements.

● All class and method contents are also blocks e.g., the class content or the
main method in the examples are blocks.

● It is advised to indent i.e. put tabs or spaces so that the inside blocks are
one tab more than the containing block. Indenting the blocks will help in
resolving the compilation errors faster and the programs will be easy to read.
Block of code

class CodeBlock{
public static void main(String arg[]){
System.out.println("In main block");
{ // LINE A
System.out.print("In ");
System.out.print("inner ");
System.out.print("block "); // LINE A1
System.out.println("One");
}
{ // LINE B
System.out.print("In ");
System.out.print("inner ");
System.out.print("block ");
System.out.println("Two"); OUTPUT
{ // LINE C
System.out.println ("Block inside inner block two"); In main block
} In inner block One
} // LINE D In inner block Two
}} Block inside inner block two
DESCRIPTION

Here we have two inner blocks starting at LINE A and LINE B. Inside the second
inner block we have one more block starting at LINE C. The class content and
the main method content are also blocks. In total there are 5 blocks in this
program.
THINGS TO TRY

● Remove the open curly brace at LINE C and check what compilation error
do you get.

● Remove the close curly brace at LINE D and see the compilation error. Is
the error same as what we got when we removed the open brace.

● Change the code to remove all the curly braces for the three blocks and
check if the output changes.

● Include LINE A1 inside one more block and see the output.
Block of code for if

class IfCodeBlock
{
public static void main(String arg[])
{
short marks = 95;

if( marks > 90 )


{
System.out.println("Excellent"); // LINE A
System.out.println("Scholarship Granted"); // LINE B
}

} OUTPUT
}
Excellent
Scholarship granted
DESCRIPTION

Here we want to print Excellent and Scholarship granted when marks are greater
than 90. If we do not include these two statements in the code block i.e. in curly
braces { }, then Scholarship granted will be printed whether or not marks are
greater than 90. Since if considers only the first statement after the condition.
Even indenting will not help, since java is free-form language and does not give
importance to spaces, tabs etc.
THINGS TO TRY

● Remove curly braces enclosing LINE A and LINE B and compile it. Change
marks to 100, 90 and 80 and see the various outputs.

● Include LINE B inside one more block i.e. place open curly brace { just
before System in LINE B and close curly brace } just after ; and before
comment // LINE B. If it is placed after // LINE B it will be considered as a
comment and throws a compilation error.
Scope Of Variables In Nested/Multiple Blocks

● Scope Of Variables - in Nested/Multiple Blocks in Java States that variables


declared in outer blocks will be accessible in inner blocks, where as variables
declared in inner blocks can not be used outside of the block.
Nestedmultiple blocks

class NestedMultipleBlocks{ System.out.println("z = " + z); {


apublic static void main(String arg[]){ // INNER BLOCK 2
int x = 10; // LINE A int y = x * 3;
int a = 20; // LINE B System.out.println("y in inner block 2 = " + y );
System.out.println("x = " + x);{ z = y;
// INNER BLOCK 1 System.out.println("z in inner block 2 = " + z );
int y = x * 2; }
System.out.println("y in inner block 1 = " + y ); // int a = 70; // Won't work // LINE D
x = 50; System.out.println("x after the blocks = " + x);
System.out.println("x in inner block 1 = " + x ); // System.out.println("y = " + y); // Won't work // LINE
} E
// LINE C System.out.println("z after the blocks = " + z); // LINE
// System.out.println("y = " + y); // Won't work F
int z = 20; OUTPUT
} x = 10
} y in inner block 1 = 20
x in inner block 1 = 50
z = 20
y in inner block 2 = 150
z in inner block 2 = 150
x after the blocks = 50
z after the blocks = 150
DESCRIPTION

Here x is valid in all lines below LINE A, a is valid in all lines below LINE B.
y declared in INNER BLOCK 1 is valid only inside that block and is not valid after
LINE C.
y can be declared again in INNER BLOCK 2 and will be valid only in that block.
z declared above INNER BLOCK 2 is valid inside INNER BLOCK 2 as well as
after the block i.e. in LINE F.
Redeclaring a again in LINE D will not work since there is already a variable with
the same name in the scope.
Trying to print y after INNER BLOCK 1 or INNER BLOCK 2 will not work since
the scope is restricted only to inside the blocks.
THINGS TO TRY

● Uncomment - the statement int a = 70; at LINE D to see the error - "a is
already defined in main"

● Uncomment - the statement System.out.println("y = " + y); at LINE E to see


the error - "cannot find symbol"

● Change int y = x * 3; to y = x * 3; in LINE C1 to see the error - "cannot find


symbol"
A

a
THANK YOU
Control statements
What you’ll learn

● Introduction to control statements


● Types
● Decision-making statements and its types
● Jump statements and its types
● Loops and its types
● Code snippets
● Gaming scenario
Through constructor
Introduction to control statements

● controls the flow of a program


● determines whether the other statements will be executed or not
● Types:
1) Decision making statements
2) Jump statements
3) Loops
Through constructor
Decision making statements

● Evaluates the expression


● Controls the flow of code based on the condition result
● Two types:
1) if
2) Switch
if statement

● Evaluates a condition
● Controls based on the condition result
● Either true or false
● Four types:
1) if
2) if-else
3) else-if
4) nested if
if statement

● Enables to enter the block of code only if condition evaluates to true


● Syntax:

if(<condition>) {

//block of code

}
if statement - Example

public class Numerics{


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
if-else statement

● The else block is executed if the condition of the if-block is evaluated as false
● Syntax:
if(<condition>) {
//block of code
}
else{
//block of code
}
if-else statement - Example
public class Numerics{
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
}else {
System.out.println("x + y is greater than 20"); }
}
else-if statement

● Contains the if-statement followed by multiple else-if statements


● Also define an else statement at the end of the chain
● Syntax:
if(<condition>) {
//block of code
}
else if{
//block of code
}
else{
//block of code
}
else-if statement - Example
public class Language{
public static void main(String[] args) {
String lang = "Java";
if(lang == "Python") {
System.out.println("language is python");
}else if (lang == "C++") {
System.out.println("lang is C++");
}else if(lang == "Java") {
System.out.println("lang is Java");
}else {
System.out.println(lang); }
}}
Nested-if statement

● if statement contains multiple if-else statements as a separate block of code.


● Syntax:
if(<condition>) {
if(<condition>) {
//block of code
} }
else if{
//block of code
}
else{
//block of code }
Nested if statement - Example

public class Language{


public static void main(String[] args) {
String lang = "Java";
if(lang == "HLL & IL") {
if(lang == “python”)
System.out.println("language is python");
}else if (lang == "C++") {
System.out.println("lang is C++");
}else if(lang == "Java") {
System.out.println("lang is Java");
}else {
System.out.println(lang); }

}}
Switch statement

● Checks the variable for the range of values defined for multiple cases
● Syntax:
switch <variable>
{
Case <option 1>:
//block of statements
Case <option n>:
//block of statements
Default:
//block of statements }
Jump statements

● Transfer the execution control to the other part of the program


● Two types:
1) break
2) continue
break

● breaks the current flow of the program


● transfers the control to the next statement outside the current flow.
● breaks the loop and switch statement - forceful terminations
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
} }
continue

● skips the specific part of the loop


● jumps to the next iteration of the loop immediately
● forceful iterations of the loop
for(int i = 0; i<= 2; i++) {
for(int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
} } }
Loops in Java

Executes a set of instructions/functions repeatedly when some conditions


become true. There are three types of loops in Java.

● for loop
● while loop
● do-while loop
For Loops

Iterates a part of the program several times if the number of iteration


is fixed.

● Simple For Loop


● Nested for loop
● For-each or Enhanced For Loop
● Labeled For Loop
Simple For Loop

Syntax:
for(Initialization; Condition; Increment/Decrement)
{
Statements;
}
For Loop

INITIALIZATION

FALSE
CONDITION

TRUE

STATEMENT

TERMINATE THE
INCR/DECR
LOOP
For Loop

class Main {
public static void main(String[] args)
i=0 i<3 o/p i++
{
0 true 0 1
for(int i = 0; i < 3; i++) {
System.out.println(i); 1 true 1 2
} 2 true 2 3
}
3 False - -
}
Example

class Main {
public static void main(String[] args) {
for(int i = 0; i < 3; i++) {
System.out.println(i);
}
System.out.println(i);
}
NOT WORKING, WHY
} ?
Example

class Main {
public static void main(String[] args) {
int i;
for(int i = 0; i < 3; i++) {
System.out.println(i);
}
}
}
NOT WORKING, WHY
?
Nested For Loop

public class Main {


public static void main(String[] args) {
for(int i = 1;i <= 3;i++) {
for(int j = 1;j <= 3;j++) {
System.out.println(i+" "+j);
}
}
}
}
Predict the output

public class Main {


public static void main(String[] args) {
for(int i = 1;i <= 5;i++) {
for(int j = 1;j <= i;j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Predict the output

public class Main {


public static void main(String[] args) {
int term = 6;
for(int i = 1;i <= term;i++) {
for(int j = term;j >= i;j--) {
System.out.print("* ");
}
System.out.println();
} } }
For Each Loop

public class Main {


public static void main(String[] args) {
int arr[] = {12,23,44,56,78};
for(int i:arr) {
System.out.println(i);
}
}
}
Infinite For Loop

public class Main {


public static void main(String[] args) {
for(;;) {
System.out.println("infinitive loop");
}
}
}
While Loop

● Iterates a part of the program several times.


● The number of iteration is not fixed
● Syntax:
while(condition)
{
//block of code

}
While Loop

CONDITION

TRUE FALSE

STATEMENT TERMINATE LOOP


Example

public class Main {


public static void main(String[] args) {
int i = 1;
while(i <= 10) {
System.out.println(i);
i++;
}
}
}
Infinite While Loop

If you pass true in the while loop, it will be infinitive while loop

while(true)
{
//code to be executed
}
Infinite While Loop

public class Main {


public static void main(String[] args) {
while(true) {
System.out.println("infinitive while loop");
}
}
}
do While Loop

● Iterates a part of the program several times.


● The number of iteration is not fixed and you must have to execute the loop
at least once.
● Syntax:
do
{
//block of code
}while(condition);
do While Loop

dO

STATEMENT

TRUE

CONDITION

FALSE
Example

public class Main {


public static void main(String[] args) {
int i = 1;
do{
System.out.println(i);
i++;
}while(i <= 10);
}
}
Infinite do While - Syntax

● If you pass true in the do-while loop, it will be infinitive do-while loop

do
{
//block of code
}while(true);
Infinite do While

public class Main {


public static void main(String[] args) {
do{
System.out.println("infinitive do while loop");
}while(true);
}
}
Predict the output

public class Main {


public static void main(String[] args) {
for(int i = 0; i <= 5; i++ )
{
System.out.println("i = " + i );
}
}
}
Predict the output

public class Main {


public static void main(String[] args) {
for(int i = 0; i < 5; i++)
{
System.out.println("Hello");
i++;
}
}
}
Predict the output
public class Main {
public static void main(String[] args) {
String s = "friends";
int x = 0;
do{
System.out.print(s.charAt(x));
x++ ;
}while (x < 2);
}
}
Predict the output

public class Main {


public static void main(String[] args) {
while(true);{
System.out.println("codemithra");
}
}
}
Predict the output

public class Main {


public static void main(String[] args) {
do{
System.out.println("Ethnus");
}while(false);
}
}
Through constructor
Code snippet

public class BreakForLoop {


public static void main(String arg[])
{
for(int i = 1; i <= 10; i++)
{
System.out.println("before breaking = " + i );
if(i == 6)
break;
System.out.println("after breaking = " + i );
}
System.out.println("for loop terminated.");
} }
Through constructor
Code snippet

public class BreakNestedForLoop {


public static void main(String[] args) {
for(int i=1;i<=3;i++) //1, 2 , 3
{
for(int j=1;j<=3;j++) //1 2
{
if(i==2&&j==2){
break; //forceful termination on inner for loop
}
System.out.println(i+" "+j); //11, 12, 13
//21,
//31, 32, 33
} } } }
Through constructor
Code snippet

public class BreakWhileLoop {


public static void main(String[] args) {
int a=1;
while(a<=10){
if(a==5)// 5==5
break; //forceful termination
System.out.print("\n\tStatement : " + a);//1 2
3 4
a++;//2
}
System.out.print("\n\tEnd of Program.");
}
}
Through constructor
Code snippet

public class BreakDoWhile {


public static void main(String[] args) {
int i=1;
do{
if(i==5) { //2==5, 3==5 4==5 5==5
i++; //6
break;
}
System.out.println(i); //1 2 3 4
i++; //2 3 4 5
}while(i<=10); //2<=10 , 3<=10, 4<=10, 5<=10
System.out.println(i);
} }
Through constructor
Code snippet

public class Continue1 {


public static void main(String[] args) {
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) { //4==4
continue; //forecful iteration
}
System.out.println(j); //01235 1235 235
}
}
}
Through constructor
Code snippet

class ContinueExample{
public static void main(String args[]) {
int first = 5, second = 20;
do {
if (first++ > --second) { //5>19, 6>18, 7>17, 8>16, 9>15, 10>15,
11>14, 12>13, 13>12
Continue ; } //14>11, 15>10
} while (first < 15);//6<15,7<15, 8<15, 9<15, 10<15, 11<15, 12<15,
13<15, 14<15,15<15
System.out.println("first = " + first + " and second = " + second);
}
}
Through constructor
Code snippet

public class ContinueNestedForLoop {


public static void main(String[] args) {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
continue;
}
System.out.println(i+" "+j);
}
}
}

}
Through constructor
Code snippet

public class ContinueWhileLoop {


public static void main(String[] args) {
int i = 1;
while(i<=10){ //1<=10 6<=10
if(i==5){ //5==5
i++; //6
continue;
}
System.out.println(i); //1 2 3 4 6...10
i++;//2 3 5
}

}}
Through constructor
Code snippet

public class ContinueDoWhileLoop {


public static void main(String[] args) {
int i=1;
do{
if(i==5){
i++; //6
continue;
}
System.out.println(i); //1 2 3 4 6
i++; //2 3 4 5 7
}while(i<=10); //3<=10
}
}
Pattern programming
What you’ll Learn

● Brief intro to pattern programming


● Benefits
● Approach
● Different patterns and programs
Pattern programming

● On the basis of different designs/patterns using characters/numbers or


combination of both
● Benefits
○ Enhances the logical thinking capabilities
● Prerequisites
○ Detailed understanding of control statements
Categories

● Star patterns
● Number patterns
● Character patterns
● Combination of numbers and characters

● Examples of the designs


○ Right triangle, left triangle, pyramid, inverted triangle, etc..
Approach

● Draw the given pattern in the blocks to have a clear representation


● Get the logic with respect to the pattern
● Imply in the code using the control statements
Rows ( i )

columns( j )
Code snippets
import java.util.Scanner;
public class Type1Program1 {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the row value");
int row = sc.nextInt();
System.out.println("Triangled stars");
for(int i = 1; i<=row; i++)
{
for(int j = 1; j<=i; j++)
System.out.print("*");
System.out.println();
} }
Code snippets
public class Type1Program2 {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the row value");
int num = sc.nextInt();
for(int i = 1; i<=num; i++)
{
for(int j= 1; j<=i;j++)
System.out.print(j);
System.out.println();
}
} }
Code snippets
public class Type1Program3 {
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
System.out.println("enter the row value: ");
int n=sc.nextInt();
for(int i=1;i<=n;i++)
{
char ch = 'A'; // extra variable initialization inside the
outer for loop to retain the initial value in every row.
for(int j=1;j<=i;j++)
System.out.print(ch++);//A
System.out.println();
}
} }
Code snippets
public class Type1Program4 {
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
System.out.println("enter the row value: ");
int n=sc.nextInt();
char ch='A';// extra variable initialization outside the outer
for loop to just print 'A' only once in the first row
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
System.out.print(ch++);
System.out.println();
}
} }
Code snippets
public class Type2Program1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the row value");
int num = sc.nextInt();
int space = num-1;
System.out.println("Triangled stars in the right side");
for(int i = 1; i<=num; i++) {
for(int k = 1; k<=space; k++)
System.out.print(" ");
for(int j = 1; j<=i; j++) {
System.out.print("*");
System.out.println();
space--; }
}
}
}
Code snippets
public class Type2Program2 { for(int j=1;j<=i;j++){
public static void main(String[] args){ if( ((i==1 )|| (i==n)) && ((j==1)
Scanner sc = new Scanner(System.in); || (j==n)) )
System.out.println("enter the row System.out.print("*");
value"); else if((j==1) || (j==i))
int n=sc.nextInt();
int ch1=1; System.out.print(ch2++);
char ch2 = 'A'; else
int space = n-1; System.out.print(ch1++);
for(int i=1;i<=n;i++){ }//end of j
for(int loop
k=1;k<=space;k++) space--;
System.out.println();
System.out.print(" "); }
}
}
}
Code snippets
public class Type3Program1 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("enter the row value");
int n=sc.nextInt();
int st=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=st;j++)
System.out.print("*");
System.out.println();
if(i<=n/2)
st++;
else
st--;
} } }
Code snippets
public class Type4Program1 {
public static void main(String[] args) {
int term = 6;
for(int i = 1;i <= term;i++) {
for(int j = term;j >= i;j--) {
System.out.print("*");
}
System.out.println();
}

}
Scanner class
What you’ll Learn

● Introduction to Java Scanner class


● Scanner Class constructors
● Scanner Class methods
Java Scanner

● Present in java.util package


● Breaks the input into tokens using a delimiter which is whitespace by
default.
● Scanner Class Declaration:

public final class Scanner

extends Object

implements Iterator<String>, Closeable


Java Scanner

● Provides nextXXX() methods to return the type of value such as


nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(),
nextFloat(), nextBoolean(), etc.

● To get a single character from the scanner, you can call


next().charAt(0) method which returns a single character.
Why Scanner

● 5-10% of the interviews will contain questions on this topic


● High demand in the market/IT industry
● To develop applications that would take the input from the user
Example

Real life example of Scanner is ATM Machine

● Cash Withdrawal
● Retrieve Mini-Statement
● Change Pin
● Based on Our Input
○ Select Option for Cash Withdrawal from Account
○ Enter the Amount
○ Enter the PIN
How to Get Java Scanner

● Scanner which reads input from the user

Scanner in = new Scanner(System.in);

● Scanner which parses the strings


Scanner in = new Scanner("Codemithra");
Scanner Class Constructors

Constructor Description
It constructs a new Scanner that produces
Scanner(File source) values scanned from the specified file.
It constructs a new Scanner that produces
Scanner(File source, String charsetName) values scanned from the specified file.
It constructs a new Scanner that produces
Scanner(InputStream source) values scanned from the specified input stream.
Scanner(InputStream source, String It constructs a new Scanner that produces
charsetName) values scanned from the specified input stream.
It constructs a new Scanner that produces
Scanner(Readable source) values scanned from the specified source.
Scanner Class Constructors

Constructor Description
It constructs a new Scanner that produces values
Scanner(String source) scanned from the specified string.
Scanner(ReadableByteChannel It constructs a new Scanner that produces values
source) scanned from the specified channel.
Scanner(ReadableByteChannel It constructs a new Scanner that produces values
source, String charsetName) scanned from the specified channel.
It constructs a new Scanner that produces values
Scanner(Path source) scanned from the specified file.
Scanner(Path source, String It constructs a new Scanner that produces values
charsetName) scanned from the specified file.
Important Methods of Scanner class

public String next() Returns the next token from the


scanner

public String nextLine() Moves the scanner position to the next


line and returns the value as a string

public int nextInt() Scans the next token as an int value

public float nextFloat() Scans the next token as a float value

public double nextDouble() Scans the next token as a double value


Scanner Class Methods

Return type Method Description


void close() It is used to close this scanner.
It is used to get the Pattern which the Scanner class is
pattern delimiter() currently using to match delimiters.
It is used to find a stream of match results that match
Stream findAll() the provided pattern string.
It is used to find the next occurrence of a pattern
constructed from the specified string, ignoring
String findInLine() delimiters.
It is used to find the next occurrence of a pattern
constructed from the specified string, ignoring
string findWithinHorizon() delimiters.
Example

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("------Welcome to Ethnus ATM-------");
System.out.println("Enter the amount to withdraw");
int amount = in.nextInt();
System.out.print("Enter the PIN: ");
int pin = in.nextInt();
System.out.println("Thanks for Using Ethnus ATM");
System.out.println("Amount you have withdrawn is:" + amount);
in.close(); } }
Scanner Class Methods

Return type Method Description


Returns true if this scanner has another token in its
boolean hasNext() input.
Checks if the next token in this scanner's input can be
interpreted as a BigDecimal using the
boolean hasNextBigDecimal() nextBigDecimal() method or not.
Checks if the next token in this scanner's input can be
interpreted as a BigDecimal using the
boolean hasNextBigInteger() nextBigDecimal() method or not.
Checks if the next token in this scanner's input can be
interpreted as a Boolean using the nextBoolean()
boolean hasNextBoolean() method or not.
Scanner Class Methods

Return type Method Description


Checks if the next token in this scanner's input can be
interpreted as a BigDecimal using the nextByte() method
boolean hasNextDouble() or not.

Checks if the next token in this scanner's input can be


boolean hasNextFloat() interpreted as a Float using the nextFloat() method or not.

Checks if the next token in this scanner's input can be


boolean hasNextInt() interpreted as an int using the nextInt() method or not.

Checks if the next token in this scanner's input can be


boolean hasNextLong() interpreted as a Long using the nextLong() method or not.
Scanner Class Methods

Return type Method Description


It is used to check if the next token in this scanner's input can
be interpreted as a Short using the nextShort() method or
boolean hasNextShort() not.
It is used to get the IOException last thrown by this Scanner's
IOException ioException() readable.

Locale locale() It is used to get a Locale of the Scanner class.


It is used to get the match result of the last scanning
MatchResult match() operation performed by this scanner.
It is used to get the next complete token from the scanner
String next() which is in use.
Scanner Class Method

Return type Method Description


BigDecimal nextBigDecimal() It scans the next token of the input as a BigDecimal.

BigInteger nextBigInteger() It scans the next token of the input as a BigInteger.


It scans the next token of the input into a boolean value and
boolean nextBoolean() returns that value.

byte nextByte() It scans the next token of the input as a byte.

double nextDouble() It scans the next token of the input as a double.


Scanner Class Method

Return type Method Description


float nextFloat() It scans the next token of the input as a float.

int nextInt() It scans the next token of the input as an Int.


It is used to get the input string that was skipped of the
String nextLine() Scanner object.

long nextLong() It scans the next token of the input as a long.

short nextShort() It scans the next token of the input as a short.


Scanner Class Method

Return type Method Description


int radix() It is used to get the default radix of the Scanner use.
It is used when remove operation is not supported by
void remove() this implementation of Iterator.

Scanner reset() It is used to reset the Scanner which is in use.


It skips input that matches the specified pattern, ignoring
Scanner skip() delimiters
It is used to get a stream of delimiter-separated tokens
Stream<String> tokens() from the Scanner object which is in use.
Scanner Class Method

Return type Method Description


It is used to get the string representation of Scanner
String toString() using.
It is used to set the delimiting pattern of the Scanner
Scanner useDelimiter() which is in use to the specified pattern.
It is used to sets this scanner's locale object to the
Scanner useLocale() specified locale.
It is used to set the default radix of the Scanner which is
Scanner useRadix() in use to the specified radix.
It is used to get the string representation of Scanner
String toString() using.
Example

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Example
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("--------Enter Your Details-------- ");
System.out.print("Enter your name: ");
String name = scan.next();
System.out.print("Enter your age: ");
int i = scan.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = scan.nextDouble();
System.out.println("Salary: " + d);
scan.close(); } }
Example
import java.util.*;
public class Main {
public static void main(String args[]) {
String str =
"Codemithra/is/a/learning/platform/";
Scanner scanner = new Scanner(str);
scanner.useDelimiter("/");
System.out.println("---Result---");
while(scanner.hasNext()) {
System.out.println(scanner.next());
}
System.out.println("Delimiter used: " +scanner.delimiter());
}
}
Through constructor
Gaming scenario!
Problem statement

Code a java program which will let the user and


computer play the “Rock,paper,scissors” game on
the console. Get the required input from the
users using the scanner class.Think, implement
the logics and conditions required to accomplish
the task using the combinations of
appropriate control statements.

Additional task

Announce the best winners from computer vs


user. Say, the user & computer plays 3 rounds of
game. The best winner is the one who has won
minimum of 2 rounds / all the 3 rounds.
Through constructor
Sample output

Note:
Also think about other combination
of choices to arrive at the optimized
game environment. And, enhance
the detailed notifications to the
users. Say, display information
about what defeats what, include
logic for draw match, notify the
same, etc..

The more you enhance the code,


more your logical thinking
Question: 01

Which of these are selection statements in


Java?

A. If

B. For

C. Continue

D. break
Question: 02

Which of these selection statements test


only for equality?
A. If

B. Switch

C. Both

D. None of the above


Question: 03

//Predict the output:


class Main {
public static void main(String args[]) {
A. 1
int var1 = 5;
B. 2
int var2 = 6;
C. 3
if ((var2 = 1) == var1)
D. 4
System.out.print(var2);
else
System.out.print(++var2);
} }
Question: 04

//Predict the output:


class Main { A. 1
public static void main(String args[]) {
int a = 4; 2
if (a <= 0) { A. 2
if (a == 0) {
System.out.println("1 "); 3
} else { A. 1
System.out.println("2 ");
} 3
} A. 3
System.out.println("3 ");
}
}
Question: 05

//Predict the output:


class Test {
public static void main(String[] args) {
boolean b = true;
A. Hello
if (b = false) {
System.out.println("HELLO"); B. Bye
} else {
C. Compilation Error
System.out.println("BYE");
} D. No output
}
}
Question: 06

//Predict the output:


class Main {
public static void main(String args[]) {
int sum = 0;
A. 5
for (int i = 0, j = 0; i < 5 & j < 5; ++i, j = i + 1)
sum += i; B. 6
System.out.println(sum);
C. 14
}
} D. Compilation error
Question: 07

//Predict the output:


class Main {
public static void main(String args[]) {
int x = 2;
A. 1,3,5,7
int y = 0;
for (; y < 10; ++y) { B. 2,4,6 8
if (y % x == 0)
C. 1,3,5,7,9
continue;
else if (y == 8) D. 1,2,3,4,5,6,7,8,9
break;
else
System.out.print(y + " ");
}
}
}
Question: 08

//Predict the output:


class Main {
public static void main(String args[]) {
int a = 5;
A. 5 10
int b = 10;
first: { B. 10 5
second: {
C. 5
third: {
if (a == b >> 1) D. 10
break second;
}
System.out.println(a);
}
System.out.println(b);
} }
Question: 09

class Main {
public static void main(String[ ] args) {
do
while (true)
A. HELLO
System.out.println("HELLO");
while (false); B. Compile Time Error
}
C. HELLO(infinitely)
}
D. NO OUTPUT
Question: 10

class Test {
public static void main(String[] args) {
do
System.out.println("FRIENDS");
A. Compile time error
while (true);
System.out.println("ENEMY"); B. FRIENDS
}
C. No output
}
D. ENEMY
Question: 11

class Test {
public static void main(String[] args) {
do {
System.out.print(1);
A. 1 2
do {
System.out.print(2); B. 2 1
} while (false);
C. 1
} while (false);
} D. 2
}
Question: 12

What is true about a break? A. Break stops the execution of entire


program
B. Break halts the execution and forces
the control out of the loop
C. Break forces the control out of the loop
and starts the execution of next
iteration
D. Break halts the execution of the loop
for certain time frame
Question: 13

public class Test {


public static void main(String[] args) {
for (int i = 0, String = “CFG "; i < 2; i++)
System.out.println("HELLO WORLD"); A. Hello World
} B. Compile Time Error
}
C. Hello World
D. Hello World, Hello World.
E. No Output
Question: 14

class Test {
public static void main(String[] args) {
int i = 0;
for (System.out.println("HI"); i < 1; i++)
A. HI HELLO PIE
System.out.println("HELLO PIE");
} B. NO OUTPUT
}
C. Compile Time Error
D. HELLO PIE
Question: 15

class Test {
public static void main(String[] args) {
for(int i=0;i<1;System.out.println("WELCOME"))
System.out.println("GREAT");
A. GREAT WELCOME
}
} B. No Output
C. Compile time error
D. GREAT WELCOME(Infinitely)
Question: 16

class Test {
public static void main(String[] args) {
boolean b = true;
if (b = false) {
A. Hello
System.out.println("HELLO");
} else { B. Bye
System.out.println("BYE");
C. Compilation Error
}
} D. No output
}
Question: 17

public class Main{


public static void main(String args[]){
int a=15;
int b=25;
if ((a<b) || (a=5)>15) A. Error
System.out.println(a); B. 15
else C. 25
System.out.println(b); D. No output
}
}
Question: 18

public class Main


{
public static void main(String args[]) {
int a=5,b=18;
if((a=3)==b) A. 3
{ B. 18
System.out.println(++a); C. 19
} D. 6
else
{
System.out.println(++b);
}
}
}
Question: 19

class Factorial
{
public static void main(String s[])
{
int number = 5; A. Factorial of 5: 1
B. Factorial of 5: 120
int factorial = 1; C. Compilation Errors
D. Factorial of 5: 625
for(int i = 2; i <= number; i++ )
{
factorial *= factorial;
}
System.out.println("Factorial of 5:” + factorial);
}
}
Question: 20

Which of the following statements is true?


1. for every 'if' there should be an 'else'.
2. for every 'else' there should be an 'if'.
3. 'if' block can exist without an 'else'.
4. 'if' condition can be used inside another 'if' A. Only 2, 3 and 4 are true.
condition. B. All of the statements are true.
C. Only 2 and 3 are true.
D. Only 3 is true.
Question: 21

public class Main


{
public static void main(String[] args) {
boolean male=false;
int age=30; A. Girl
if(male) B. Woman
if(age<20) C. Boy
System.out.println("Boy"); D. Man
else
System.out.println("Man");
else
if(age<20)
System.out.println("Girl");
else
Question: 22

public class Main


{
public static void main(String[] args) {
boolean male=false;
A. Congratulations
int marks=80; Distinction
if(marks>70) { A. Pass
Distinction
System.out.println("Distinction");
A. Distinction
System.out.println("Congratulations"); Congratulations
} A. Compilation Errors
else if(marks>35) {
System.out.println("Pass");
}
else {
System.out.println("Fail");
System.out.println("Better Luck Next Time");
Question: 23
public class Main {
public static void main(String[] args) {
int day=4; A. Thursday
switch(day) {
case 1: B. Compilation Errors
System.out.println("Monday"); C. Runtime Error
case 2:
System.out.println("Tuesday"); D. Thursday
case 3: Friday
System.out.println("Wednesday");
case 4: Weekend
System.out.println("Thursday");
case 5:
System.out.println("Friday");
default:
System.out.println("Weekend");
break;
}
}
}
Question: 24

Which of the following two types are


acceptable as expressions for the switch
statement? The expression in the below A. 1 and 3
example is expr.
switch(expr) B. 2 and 4
{
C. 3 and 5
default:
System.out.println("Hello"); D. 4 and 6
}
}
}

1. byte 2. long 3. char 4. float 5. double 6.


boolean
Question: 25

public class Main


{
public static void main(String[] args)
{ A. No output
if(1>2){ B. 1 is greater than 2
System.out.println("1 is greater than 2");
} C. 2 is greater than 1
}
} D. Runtime error
/ethnuscodemithra Ethnus /ethnus /code_mithra
Codemithra

https://learn.codemithra.com

codemithra@ethnus.com +91 7815 095 +91 9019 921


095 340
Pattern Question In Java
Sample 1

i stars n

n = 3 0 1 3

* 1 2 3
** 2 3 3
***
i = 0 to 2 {0, 1, 2}
stars = i + 1
Sample 1
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
i = 0 to 2 {0, 1, 2} for(int i = 0; i < n; i++) {
int stars = i + 1;
stars = i + 1 for(int j = 0; j < stars; j++) {
System.out.print("*");
}
System.out.print("\n");
}
}
}
Sample 2

i stars n

n = 3 0 3 3

*** 1 2 3
** 2 1 3
*
i = 0 to 2 {0, 1, 2}
stars = n - i
Sample 2

import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
i = 0 to 2 {0, 1, 2} int n = sc.nextInt();
for(int i = 0; i < n; i++) {
stars = n - i int stars = n - i;
for(int j = 0; j < stars; j++) {
System.out.print("*");
}
System.out.print("\n");
}
}
}
Sample 3

First 3 rows Last 3 rows

i stars n i stars n
n = 3
0 1 3 0 3 3
*
** 1 2 3 1 2 3
*** 2 3 3 2 1 3
**
* i = 0 to 2 {0, 1, 2} i = 0 to 2 {0, 1, 2}

stars = n - i stars = n - i
Sample 3

i = 0 to 2 {0, 1, 2}
stars = i + 1
i = 1 to 2 {1, 2}
stars = n - i
Sample 3
import java.util.Scanner; for(int i = 1; i < n;
class Main { i++) {
public static void main(String[] int stars = n - i;
args) { for(int j = 0; j <
Scanner sc = new stars; j++) {
Scanner(System.in);
int n = sc.nextInt(); System.out.print("*");
for(int i = 0; i < n; i++) { }
int stars = i + 1;
for(int j = 0; j < stars; j++) System.out.print("\n");
{ }
System.out.print("*"); }
} }
System.out.print("\n");
}
Question

To print a solid and hollow rectangle using stars


Question

Hollow Diamond Inscribed in a Rectangle


Question

To print the various below shown Pyramid pattern programs using stars
Question

Pascal’s Triangle Pattern Program


Question

Floyd’s Triangle Pattern Program


Question

To print the various below shown Pyramid pattern programs using numbers
Question

To print the various below given Diamond pattern programs using star
Question

To print the various below given palindromic pyramid pattern programs


using numbers and alphabet
Question

To print the various below given Diamond pattern programs using numbers
and stars
PATTERN
PROGRAMS USING
LOOPS IN JAVA
STAR PATTERNS IN JAVA
1. Sandglass Star Pattern Enter the number of rows: 5
import java.util.Scanner; System.out.println("");
public class Ethnus }
{ for (int i= rows-1; i>= 0; i--)
public static void main(String[ ] args) {
{ for (int j=0; j< i ;j++)
Scanner sc = new Scanner(System.in); {
System.out.println("Enter the number of System.out.print(" ");
rows: "); }
int rows = sc.nextInt(); for (int k=i; k<=rows-1; k++)
for (int i= 0; i<= rows-1 ; i++) {
{ System.out.print("*" + " ");
for (int j=0; j <i; j++) }
{ System.out.println("");
System.out.print(" "); }
} sc.close();
for (int k=i; k<=rows-1; k++) }
{ }
System.out.print("*" + " "); }
STAR PATTERNS IN JAVA
2. Right Triangle Star Pattern
public class Ethnus {
{ System.out.print("* "); // print star
public static void rightTriangle(int n) }
{ System.out.println(); // ending line after
int i, j; each row
for(i=0; i<n; i++) //outer loop for }
number of rows(n) }
{ public static void main(String args[ ])
for(j=2*(n-i); j>=0; j--) // inner loop for {
spaces int n = 5;
{ rightTriangle(n);
System.out.print(" "); // printing space }
} }
for(j=0; j<=i; j++) // inner loop for
columns
STAR PATTERNS IN JAVA
3. Right Pascal’s Triangle Enter the number of rows: 5
import java.util.Scanner; System.out.println("");
public class Ethnus }
{ for (int i=rows-1; i>=0; i--)
public static void main(String[ ] args) {
{ for(int j=0; j <= i-1;j++)
Scanner sc = new Scanner(System.in); {
System.out.println("Enter the number System.out.print("*"+ " ");
of rows: "); }
int rows = sc.nextInt( ); System.out.println("");
for (int i= 0; i<= rows-1 ; i++) }
{ sc.close( );
for (int j=0; j<=i; j++) }
{ }
System.out.print("*"+ " ");
}
STAR PATTERNS IN JAVA
4. Diamond Shape Pattern Program in Java: Enter the number of rows: 5
import java.util.Scanner; System.out.print("*");
public class Ethnus }
{ System.out.println("");
public static void main(String args[]) }
{ space = 1;
int n, i, j, space = 1; for (j = 1; j<= n - 1; j++)
System.out.print("Enter the number of rows: "); {
Scanner s = new Scanner(System.in); for (i = 1; i<= space; i++)
n = s.nextInt(); {
space = n - 1; System.out.print(" ");
for (j = 1; j<= n; j++) }
{ space++;
for (i = 1; i<= space; i++) for (i = 1; i<= 2 * (n - j) - 1; i++)
{ {
System.out.print(" "); System.out.print("*");
} }
space--; System.out.println("");
for (i = 1; i <= 2 * j - 1; i++) }}}
{
STAR PATTERNS IN JAVA
5. Downward Triangle Star Pattern Enter the number of rows: 5
import java.util.Scanner; {
public class Ethnus System.out.print("*" + " ");
{ }
public static void main(String[ ] args) System.out.println( );
{ }
Scanner sc = new Scanner(System.in); sc.close( );
System.out.println("Enter the number of }
rows: "); //takes input from user }
int rows = sc.nextInt( );
for (int i= rows-1; i>=0 ; i--)
{
for (int j=0; j<=i; j++)
NUMERIC PATTERN IN JAVA
6. Pascal’s Triangle Program in Java
import java.util.Scanner; System.out.printf("%4d", number);
public class Ethnus number = number * (i - j) / (j + 1);
{ }
public static void main(String[ ] args) System.out.println( );
{ }
int n = 5;
for (int i = 0; i < n; i++) }
{
int number = 1; }
System.out.printf("%" + (n - i) * 2 + "s",
"");
for (int j = 0; j <= i; j++)
{
NUMERIC PATTERN IN JAVA
7. Diamond Pattern Program in Java
import java.util.Scanner; int n = 3;
public class Ethnus for (int j = 0; j<= n - i; j++)
{ {
public static void main(String[ ] args) System.out.print(" ");
{ }
for (int i = 1; i <= 4; i++) for (int k = i; k >= 1; k--)
{ {
int n = 4; System.out.print(k);
for (int j = 1; j<= n - i; j++) }
{ for (int l = 2; l <= i; l++)
System.out.print(" "); {
} System.out.print(l);
for (int k = i; k >= 1; k--) }
{ System.out.println();
System.out.print(k); }
}
for (int l = 2; l <= i; l++) }
{ }
System.out.print(l); }
NUMERIC PATTERN IN JAVA
8. Simple number program
public class Ethnus // ending line after each row
{ System.out.println( );
public static void printNums(int n) }
{ }
int i, j,num; public static void main(String args[ ])
for(i=0; i<n; i++) // outer loop for rows {
{ int n = 5;
num=1; printNums(n);
for(j=0; j<=i; j++) // inner loop for rows }
{ }
// printing num with a space
System.out.print(num+ " ");
//incrementing value of num
num++;
}
NUMERIC PATTERN IN JAVA
9. Binary Number Pattern Enter the number of rows: 5
import java.util.Scanner; num = (num == 0)? 1 : 0;
public class Ethnus }
{ }
public static void main(String[ ] args) else
{ {
Scanner sc = new Scanner(System.in); num = 1;
System.out.println("Enter the number of for (int j = 1; j <= rows; j++)
rows: "); {
int rows = sc.nextInt( ); System.out.print(num);
for (int i = 1; i <= rows; i++) num = (num == 0)? 1 : 0;
{ }
int num; }
if(i%2 == 0) System.out.println( );
{ }
num = 0; sc.close( );
for (int j = 1; j <= rows; j++) }
{ }
System.out.print(num);
NUMERIC PATTERN IN JAVA
10. Zeros/ ones Pattern Programs Enter the number of rows: 5
import java.util.Scanner; {
public class Ethnus System.out.print(0);
{ }
public static void main(String[ ] args) else
{ {
Scanner sc = new Scanner(System.in); System.out.print(1);
System.out.println("Enter the number of }
rows: "); }
int rows = sc.nextInt( ); System.out.println( );
for (int i = 1; i <= rows; i++) }
{ sc.close( );
for (int j = 1; j <= i; j++) }
{ }
if(j%2 == 0)
ALPHABET/ CHARACTER PATTERNS IN JAVA
11. K Shape Character Pattern Program
import java.util.Scanner; for (int i = 0; i<= 5; i++)
public class Ethnus {
{ int alphabet = 65;
public static void main(String[ ] args) for (int j = 0; j <= i; j++)
{ {
for (int i = 5; i >= 0; i--) System.out.print((char) (alphabet + j) + " ");
{ }
int alphabet = 65; System.out.println( );
for (int j = 0; j <= i; j++) }
{ }
System.out.print((char) (alphabet + j) + " "); }
}
System.out.println( );
}
ALPHABET/ CHARACTER PATTERNS IN JAVA

12. Right Alphabetic triangle


import java.util.Scanner;
public class Ethnus
{
public static void main(String[ ] args)
{
int alphabet = 65;
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= i; j++)
{
System.out.print((char) (alphabet + j) + " ");
}
System.out.println( );
}
}
}
THANK YOU
Inner Classes
Introduction

Inner class means one class which is a member of another class. There are basically
four types of inner classes in java.

● Nested Inner class


● Method Local inner classes
● Anonymous inner classes
● Static nested classes
NESTED INNER CLASSES

Nested Inner class can access any private instance variable of outer class. Like any
other instance variable, we can have access modifier private, protected, public and
default modifier.

Like class, interface can also be nested and can have access specifiers.
NESTED INNER CLASSES

class Outer {
class Inner {
public void show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
STATIC AND INNER CLASS

We can’t have static method in a nested inner class because an inner class is
implicitly associated with an object of its outer class so it cannot define any
static method for itself
class Outer {
void outerMethod() {
System.out.println("inside outerMethod");
}
class Inner {
public static void main(String[] args){
System.out.println("inside inner class Method");
}
}
}

The above code will lead to an error


METHOD LOCAL INNER CLASSES

Inner class can be declared within a method of an outer class. In the following
example, Inner is an inner class in outerMethod().
METHOD LOCAL INNER CLASSES

class Outer {
void outerMethod() {
System.out.println("inside outerMethod");
class Inner {
void innerMethod() {
System.out.println("inside innerMethod");
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class Main {
public static void main(String[] args) {
Outer x = new Outer();
x.outerMethod();
}
}
METHOD LOCAL INNER CLASSES

class Outer {
void outerMethod() {
int x = 98;
System.out.println("inside outerMethod");
class Inner {
void innerMethod() {
System.out.println("x= "+x);
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class Main {
public static void main(String[] args) {
Outer x=new Outer();
x.outerMethod();
}
}
METHOD LOCAL INNER CLASSES

class Outer {
void outerMethod() {
int x = 98;
System.out.println("inside outerMethod");
class Inner {
void innerMethod() {
int x = 100;
System.out.println("x= "+x);
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class Main {
public static void main(String[] args) {
Outer x=new Outer();
x.outerMethod();
}
}
STATIC NESTED CLASSES

class Outer {
private static void outerMethod() {
System.out.println("inside outerMethod");
Static nested classes }
static class Inner {
are not technically an static void method() {
inner class. They are System.out.println("inside inner class Method");
like a static member outerMethod();
}
of outer class. }
}
class Main {
public static void main(String args[]) {
Outer.Inner.method();
}
}
ANONYMOUS INNER CLASSES

Anonymous inner classes are declared without any name at all. They are created in
two ways.
● As subclass of specified type
● As implementer of the specified interface

We are going to create have two class Demo and Main. Here Demo act as super class
and anonymous class acts as a subclass, both classes have a method show(). In
anonymous class show() method is overridden.
METHOD LOCAL INNER CLASSES

class Demo {
void show() {
System.out.println("I am in show method of super class");
}
}
class Main {
static Demo d = new Demo() {
void show() {
super.show();
System.out.println("I am in Main class");
}
};
public static void main(String[] args){
d.show();
}
}
AS IMPLEMENTER OF THE SPECIFIED INTERFACE

class Main {
static Hello h = new Hello() {
public void show() {
System.out.println("I am in anonymous class");
}
};
public static void main(String[] args) {
h.show();
}
}
interface Hello {
void show();
}
AS IMPLEMENTER OF THE SPECIFIED INTERFACE

We have created an object of anonymous inner class but this anonymous inner
class is an implementer of the interface Hello.

Any anonymous inner class can implement only one interface at one time. It can
either extend a class or implement interface at a time.
QUESTION

What is NOT a type of inner classes?

A. Nested Inner class

B. Method Local inner class

C. Anonymous inner class

D. Dynamic inner class

Answer: D
QUESTION

Non-static nested classes have access to _____________ from enclosing class.

A. Private members

B. Protected members

C. Public members

D. All members

Answer: D
QUESTION

Use of nested class ____________ encapsulation.

A. Increases

B. Decreases
C. Doesn’t affect
D. Slightly decreases

Answer: A
QUESTION

A nested class can have its own static members.

A. True
B. False

Answer: B
QUESTION

How to create object of the inner class?

A. OuterClass.InnerClass innerObject = outerObject.new InnerClass();


B. OuterClass.InnerClass innerObject = new InnerClass();
C. InnerClass innerObject = new outerObject.InnerClass();
D. OuterClass.InnerClass = outerObject.new InnerClass();

Answer: A
QUESTION

If a declaration of a member in inner class has the same name as that in the
outer class, then ________________ enclosing scope

A. Outer declaration shadows inner declaration in


B. Inner declaration shadows outer declaration in
C. Declaration gives compile time error
D. Declaration gives runtime error

Answer: B
QUESTION

class Dog {
String name;
class Bone {
A. Bone of size 5
int size; B. Error
} C. Bone of size 0
static void stopBark(int size) { D. Bone of size null
Bone b = new Bone();
b.size = size;
System.out.println("Bone of size " + b.size);
}
}
class Main {
public static void main(String[] args) {
Dog.stopBark(5);
}
} Answer: B
QUESTION

class Dog {
String name;
static class Bone {
A. Bone of size 5
static int size; B. Error
} C. Bone of size 0
static void stopBark(int size) { D. Bone of size null
Bone.size = size;
System.out.println("Bone of size " + Bone.size);
}
}
class Main {
public static void main(String[] args) {
Dog.stopBark(5);
}
}
Answer: A
QUESTION

class Dog {
String name;
static class Bone {
A. Bone of size 5
int size; B. Error
} C. Bone of size 0
static void stopBark(int size) { D. Bone of size null
Bone.size = size;
System.out.println("Bone of size " + Bone.size);
}
}
class Main {
public static void main(String[] args) {
Dog.stopBark(5);
}
}
Answer: A
QUESTION

class Dog {
String name;
static class Bone {
A. Bone of size 5
private static int size; B. Error
} C. Bone of size 0
static void stopBark(int size) { D. Bone of size null
Bone.size = size;
System.out.println("Bone of size " + Bone.size);
}
}
class Main {
public static void main(String[] args) {
Dog.Bone.size = 5;
Dog.stopBark(5);
}
} Answer: B
QUESTION

class Dog {
String name;
private static class Bone {
A. Bone of size 5
static int size; B. Error
} C. Bone of size 0
static void stopBark(int size) { D. Bone of size null
Bone.size = size;
System.out.println("Bone of size " + Bone.size);
}
}
class Main {
public static void main(String[] args) {
Dog.Bone.size = 5;
Dog.stopBark(5);
}
} Answer: B
QUESTION

class Dog {
String name;
class Bone {
A. Bone of size 5
static int size; B. Error
} C. Bone of size 0
static void stopBark(int size) { D. Bone of size null
Bone.size = size;
System.out.println("Bone of size " + Bone.size);
}
}
class Main {
public static void main(String[] args) {
Dog.Bone.size = 5;
Dog.stopBark(5);
}
} Answer: B
QUESTION

class Outer {
static int x = 98;
void outerMethod() {
A. x= 100
static class Inner { B. Error
void innerMethod() { C. x= 98
x = 100; D. x= 0
System.out.println("x= " + x);
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class Main {
public static void main(String[] args) {
Outer x=new Outer(); Answer: B
x.outerMethod();
}
}
QUESTION

class Outer {
class Inner {
void innerMethod() {
A. x= 100
int x = 100; B. NullPointerException
System.out.println("x= " + x); C. Error in creating object
} D. x= 0
}
}
class Main {
public static void main(String[] args) {
Outer x = new Outer();
Outer.Inner i = x.new Inner();
x = null;
i.innerMethod();
}
} Answer: B
QUESTION

class Outer {
class Inner {
void innerMethod() {
A. x= 100
int x = 100; B. NullPointerException
System.out.println("x= " + x); C. Error: Accessing non static
} from static context
}
} D. x= 0
class Main {
public static void main(String[] args) {
Outer x = new Outer();
x.Inner.innerMethod();
}
}

Answer: C
Java Abstract Class
Java Abstract Class

● aWe have seen the class hierarchies - Entertainments example in Java Class
Inheritance and IceCreamPrices example in Inheritance Example Program To
Remove Duplicate Code.

● The class hierarchies look similar except that there is minor difference
between them. IceCream is a concrete super-class where as Entertainment is
an abstract super-class. The difference is explained below.
A

● In reality IceCream can exist, even with out FruitSaladWithIceCream, where


as Entertainment can not exist on its own. It has to be either Movie, Drama or
Circus or some other entertainment.
● Similarly Metal is an abstract class, since for we to show the Metal, we need
to either show Gold or Iron or some thing else. If we had Mobile and
MobileWithCamera, then Mobile would be a concrete class since it can exists
on its own.
● IceCream and Mobile are examples of concrete super-classes, where as
Entertainment, Metal and Shape are examples of abstract super-classes.
A

In Java every class defined is by default concrete class, but if we want to


implement abstract class, we need to use the abstract keyword before the class
to mark a class as abstract class.
abstract

abstract class Shape


{
}

class Rectangle extends Shape


{
}
A

Here we have created an abstract class called Shape and a concrete class called
Rectangle. Abstract class is prefixed with the keyword abstract, where as for
concrete class we need not mention any keyword.
Shape shape1; // Can create a reference of abstract class
Shape shape2 = new Shape(); // WILL NOT WORK. Can not create an object of abstract class

Rectangle rect1 = new Rectangle(); // Can create reference and object of a concrete class
shape1 = rect1; // Can assign concrete sub-class reference to abstract super-class reference
A

We can only create a reference for an abstract class, but can not create (or
instantiate) an object of abstract class.

We can create both reference and object for any concrete class.

We can assign a concrete sub-class reference to abstract super-class


reference. i.e. rect1 can be assigned to shape1.

The other advantage of abstract classes is we can define abstract methods. They
are explained in Abstract Method In Java.
Abstract Method In Java

As discussed in Java Abstract Class, an abstract classes do not map to real life
objects and they can not exist on their own, with out taking the form any of its
concrete sub-classes. e.g., Shape can not exist on it own, it has to be either
Rectangle or Square or Circle.

Abstract methods are those methods which have only the declaration but do not
have a definition. Declaration means creating only the method signature (the
method name, parameters and return type), but no method body, where as
definition means creating the method signature and the method body as well.
Calculate Areas

For e.g., we know that every Shape has an area, but we do not know how to
calculate the area, until we know what Shape it is. This is because the area
calculation for Rectangle is different from the area calculation of Triangle, which
is different from that of the Circle. So we will declare that we have a method
called getArea() in Shape, but only define or implement the logic of calculating
the area in there respective concrete sub-classes.
A

class CalculateAreas{
public static void main(String arg[]){
Rectangle rect = new Rectangle(5.25, 4.0);
System.out.println("Area of rectangle is " + rect.getArea());

Circle circle = new Circle(7.5);


System.out.println("Area of circle is " + circle.getArea());
}}
abstract class Shape{
abstract double getArea(); // LINE A
}
class Rectangle extends Shape{
double length;
double breadth;
Rectangle(double length, double breadth){
this.length = length;
this.breadth = breadth;
}
A
double getArea(){
return length * breadth;
}
}
class Circle extends Shape{
double radius;
Circle(double radius){
this.radius = radius; OUTPUT
}
double getArea(){ Area of rectangle is 21.0
return 3.14 * radius * radius; Area of circle is 176.625
}
}

As shown in the above program at LINE A, the abstract method does not have
any method body. The semicolon should be placed as soon as the method
signature is complete. Please read Rules For Abstract Methods and Abstract
Classes for more details.
DESCRIPTION

Here we have created an abstract Shape class and two concrete classes namely
Rectangle and Circle which extends from the Shape class. We have
implemented the getArea() method in the sub-classes. Please note that every
sub-class extending from an abstract class should implement all the abstract
methods, otherwise it will cause compilation errors.
THINGS TO TRY

Define one more sub-class Triangle which extends from Shape class. Create a
constructor, which takes the parameters base and height. Also implement the
getArea() method. Area of triangle is (base * height) / 2.0

Add one more abstract method getPerimeter() in the Shape class and
implement that method in Rectangle and Circle.

Define one more sub-class Polygon which extends from Shape. Do not define
any constructors or methods in that class including the getArea() method.
Observe the compilation error you get.
Of the below, what is a bad example of Abstract class?

A. Metal
B. Shape
C. IceCream
D. Entertainment

C. IceCream
Rules For Abstract Methods and Abstract Classes

● There are few things we need to keep in mind when working with abstract
methods and abstract classes.

● The rules for abstract methods and abstract classes are:

● A class can be marked as abstract with out containing any abstract method.
But if a class has even one abstract method, then the class has to be an
abstract class.
A

aabstract class A
{
// Valid, even with out any abstract methods
}

class B // Invalid, class B should be abstract, since it has abstract method.


{
abstract void method1();
}
An abstract class can have one or more abstract methods.

aabstract class C
{
abstract void method1();

abstract double method2(int x, int y);

abstract boolean method3(char z);


}
An abstract class can have both abstract and non abstract (or concrete)
method.
aabstract class D
{
void method1()
{
System.out.println("I am a concrete method");
}

abstract double method2(int x, int y);

int method3(double z)
{
System.out.println("I am also a concrete method");
}

abstract boolean method4(char z);


}
The abstract method should not have method body. Even empty flower
braces { } are not allowed.
a
abstract class A
{
abstract void method1(); // Valid

abstract void method2() {} // Invalid - since it has method body

Any sub-class extending from an abstract class should either implement all the
abstract methods of the super-class or the sub-class itself should be marked as
abstract.
A

a
abstract class A{ class D extends A{
abstract void method1(); void method1(){
abstract void method2(); System.out.println("Method1 implemented here.");
} }
class B extends A{ // Invalid, class D should be marked as abstract, since
// Invalid since B does not implement method2 is not implemented.
the abstract methods }
} abstract class E extends A{
abstract class C extends A{ void method1(){
// Valid since C is marked as abstract, System.out.println("Method1 implemented here.");
even though the abstract methods are }
not implemented, // Even though method2 is not implemented, class D is
} marked as abstract, so it is Valid.
}
A

class F extends A
a
{
// Valid since both methods are implemented here.
void method1()
{
System.out.println("Method1 implemented here.");
}

void method2()
{
System.out.println("Method2 implemented here.");
}
}
If an abstract class contains multiple methods, it is not necessary that all the methods of the
abstract class are implemented in the immediate sub-class. Few of them can be
implemented in sub-sub-classes or any where else in the sub-class hierarchy. But for a
class to be concrete, all the abstract methods in its super-class must be implemented.
A

aabstract class X{
abstract void method1();
abstract void method2();
}
abstract class Y extends X{
void method1(){
System.out.println("Method1 implemented here.");
}}
class Z extends Y{
void method2(){
System.out.println("Method2 implemented here.");
}
}
A

It is not necessary to add the abstract methods only in the super most class, we
can add more abstract methods in the sub-classes.
abstract class X class Z extends Y
{ {
abstract void method1(); void method1()
} {
System.out.println("Method1 from class X implemented
abstract class Y extends X here.");
{ }
abstract void method2();
} void method2()
{
System.out.println("Method1 from class Y implemented
here.");
}
}
Creating Array Of Objects In Java

In Java Array we have discussed about the arrays of primitive data types. We
can also create array of objects references and initialize data for each reference
(or element) of the array. Objects references are explained in Java Objects
References

class Student
{
String name;
int marks;
char section;
}
A

If we have a class Student, we can create an array of the references of the


Student as shown below. Here we have a created an array of size 2 and with
name students.

Student[] students = new Student[2];

Please note that, when we create an array, only the references are created and
not the objects. Hence we need to create the objects separately as shown below
at LINE A and LINE B.
students[0] = new Student(); // LINE A
students[1] = new Student(); // LINE B
A

Once the Student objects are created, then can be accessed using the dot
operator (.) as usual.

students[0].name = "David";
students[0].marks = 80;
students[0].section = 'A';

students[1].name = "Pete";
students[1].marks = 72;
students[1].section = 'B';

The program To Print Student Details Using Classes In Java shows an working
example of references array.
A

a
A

a
THANK YOU
Topic/Courseto JAVA
Introduction
Sub-Topic (Example: name of college)

Program Internal
Why and How Java?
• History of Java

• Why Java?

• Where Java?

• Difference between JDK, JRE, JVM


Compiling our first Program
• Install the JDK if you don't have installed it.

• Set path of the jdk/bin directory.

• Create the java program (preferred notepad)

• Compile and run the java program (Assuming program is saved as Hello.java

• For compiling : javac Hello.java

• For executing : java Hello


1 public class Main
2 {
3 public static void main(String[] args)
4 {
5 System.out.println(“Welcome to FACE”);
6 }
7 }
8
9
10
11
12
13
14
15
Output
Welcome to FACE
During Compile time
After writing our first program, we compile them.

Hello.class can be used in different operating system


During runtime
Types of Java Application
• Standalone Application

• Web Application

• Enterprise Application

• Mobile Application
Types of Java Editions
• Java SE – Standard Edition

• Java EE – Enterprise Edition

• Java ME – Micro Edition

• JavaFX
JVM Architecture
• JVM gives the definitions …
• JVM works with …
• Memory area
• Loads code
• Class file format
• Verifies code
• Register set
• Executes code
• Garbage-collected heap
• Provides runtime Environment
• Fatal error reporting etc.
JVM Architecture
Path Setting
• Temporary Path

• Permanent Path

• Use of editors – Sublime editor, code block

• Notepad – Execute a program


Why is JAVA Platform Independent?
Why is JAVA both interpreted and
compiled language?
Why is JAVA both interpreted and
compiled language?
Why is JAVA slow?
THANK YOU
Path Setting - JAVA
Structure of Programming
Structure of Java program
• Documentation Section

• Package Statement

• Import Statements

• Interface Statement

• Class Definition

• Main Method Class

• Main Method Definition


1 //Sample Program Documentation Section
2 import java.util.* Import statement
3 interface MyInterface Interface statement
4 {
5 public void method();
6 }
7 class Sample implements MyInterface Main method class
8 {
9 public void method() Method definition
10 {
11 System.out.println(“Sample");
12 }
13 public static void main(String arg[]) Main method definition
14 {
15 MyInterface obj = new Demo();
16 obj.method();
17 }
18 }
19
20
21
22
Documentation Section
• Comment line

• Comments are beneficial for the programmer

• Optional

• Used in Corporate programs


Package Statement
• Package is a group of classes

• Optional

• Keyword

• if you want to declare many classes within one element, then you can
declare it within a package
Import Statement
• Keyword

• Used to import built-in and user-defined packages into your java source
file

• Use the '*' character to declare all the classes belonging to the package.

• Can import both Built in packages and user defined packages


Interface Statement
• Keyword

• Optional

• Similar to classes

• Includes a group of method declarations

• Can be used when programmers want to implement multiple inheritances


within a program
Class Definition
• Java can contain multiple classes

• Class is the most important segment inside a java program

• A class declaration is made up of the following parts:

• Modifiers • Keywords

• Class name • Class body within curly brackets {}


Main method class
• Java stand-alone program requires the main method as the starting point
of the program

• There may be many classes in a Java program, and only one class defines
the main method

• Methods contain data type declaration and executable statements.


Question 1
Java source code is compiled into __________

A) Source code
B) Byte code
C) .obj
D) .exe
Question 2
Which of the tool is used to compile java code ?

A) java
B) javadoc
C) jar
D) javac
What is javac?
Question 3
Which of the following tool used to execute java code.

A) java
B) javadoc
C) jar
D) javac
Question 4
What is use of interpreter?

A) They convert bytecode to machine language code


B) They read high level code and execute them
C) They are intermediated between JIT and JVM
D) It is a synonym for JIT
Question 4
What is use of interpreter?

A) They convert bytecode to machine language code


B) They read high level code and execute them
C) They are intermediated between JIT and JVM
D) It is a synonym for JIT
THANK YOU
Data Types
Data Types

Primitive data-types Non-primitive data-types


• byte • Strings
• int • Arrays
• short • Classes
• long ….
• char
• Boolea
n
• float
Primitive Data Types
Data – Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

short 2 bytes Stores whole numbers from -32,768 to 32,767

long 8 bytes Stores whole numbers from -9,223.372,036.854,775.808 to


9,223.372,036,854,775,808
char 2 bytes Stores a single character/letter

boolean 1 byte Stores true or false values

float 4 bytes Stores fractional numbers from 3.4e−038 to 3.4e+038. Sufficient


for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers from 1.7e−308 to 1.7e+038. Sufficient
for storing 15 decimal digits
BYTE
• Byte stores from -128 and 127.

• Can be used instead of int or other integer types to save memory.

byte myNum = 100;


System.out.println(myNum);
SHORT
• short stores from -32768 to 32767:

short myNum = 5000;


System.out.println(myNum);
INT
• int stores from -2147483648 to 2147483647.

• preferred data type when we create variables with a numeric value.

int myNum = 100000;


System.out.println(myNum);
LONG
• long stores from -9223372036854775808 to
9223372036854775808.

• Used when int is not large enough to store the value.

• you should end the value with an "L":

long myNum = 15000000000L;


System.out.println(myNum);
Floating Point Types
FLOAT
• float can store fractional numbers from 3.4e−038 to 3.4e+038.

• should end the value with an "f":


float myNum = 5.75f;
System.out.println(myNum);
DOUBLE
• Double can store fractional numbers from 1.7e−308 to 1.7e+038.

• you should end the value with a "d":

double myNum = 19.99d;


System.out.println(myNum);
Use float or double?
BOOLEAN
• declared with the boolean keyword

• can only take the values true or false:

boolean isJavaFun = true;


boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
STRING
• The String data type is used to store a sequence of characters
(text).

• String values must be surrounded by double quotes:


String greeting = "Hello World";
System.out.println(greeting);
CHARACTER
• The char data type is used to store a single character.

• A char value must be surrounded by single quotes, like 'A' or 'c':

char myGrade = 'B';


System.out.println(myGrade);
WHY CHAR REQUIRES 2 BYTES IN JAVA?
IS STRING A NINTH TYPE?
WHY DO WE NEED DATA-TYPES?
IS IT REQUIRED ?
VARIABLES
What is a variable ?
• A variable which holds value, during the life of a Java program.

• Every variable is assigned a data type which designates the type and
quantity of value it can hold.

• In order to use a variable in a program you to need to perform 2 steps


--Variable Declaration
--Variable Initialization
Variable Declaration
To declare a variable, you must specify the data type & give the variable a
unique name.

Variable-
Data-type
name

int count;
Container
named “count”
holding a value
To initialize a variable, you must assign it a valid value. 100

count=100;
100

count
You can combine variable declaration and initialization.

int count=100;
NAMING CONVENTION OF VARIABLES
• can start with underscore(‘_’) but not with digits.

• Should be mnemonic i.e, designed to indicate to the casual observer the


intent of its use.

• Can use _(underscore), digits and letters.

• Should not use any reserved word.


TYPES OF VARIABLES

Local variables Instance variables Static variables


Consider this code snippet
class Guru99
{
int data = 99; //instance variable
static int a = 1; //static variable
void method()
{
int b = 90; //local variable
}
}
Non-static variable V/S Static variable
Non-static variable Static variable

1. Memory is allocated multiple time 1. Memory is allocated for these


whenever a new object is created. variable only once in the program.
2. Non-static variable also known as 2. Memory is allocated at the time
instance variable while because of loading of class so that these
memory is allocated whenever are also known as class variable.
instance is created. 3. Static variable are common for
3. Non-static variable are specific to every object that means there
an object memory location can be sharable
4. Non-static variable can access by every object reference or same
with object reference. class.
4. Static variable can access with
class reference.
WHAT IS WIDENING?
Consider this code snippet
public class Test Can you predict the output?
{
public static void main(String[] args) YOL
{ O
System.out.print("Y" + "O");
System.out.print('L' + 'O'); YO15
} 5
}
Now, try to predict the output
YOLO
public class Test
{
public static void main(String[] args) YO7679
{
System.out.print("Y" + "O");
System.out.print('L');
System.out.print('O');
}
}
RULES FOR WIDENING PRIMITVE CONVERSION
• The result of adding Java chars, shorts or bytes is an int.
• If either operand is of type double, the other is converted to
double.
• Otherwise, if either operand is of type float, the other is
converted to float.
• Otherwise, if either operand is of type long, the other is
converted to long.
• Otherwise, both operands are converted to type int
WHAT IS NARROWING?
NARROWING OR EXPLICIT TYPE-CASTING
If we want to assign a value of larger data type to a smaller data
type we perform explicit type casting or narrowing.

• This is useful for incompatible data types where automatic conversion


cannot be done.

• Here, target-type specifies the desired type to convert the specified


value to.
Guess the output
public class Test
{
public static void main(String[] argv) Error
{
char ch = 'c';
int num = 88;
ch = num;
}
}
Now, try Initialization
Variable to predict the output

10.5
10
THANK YOU
Classes and Objects
Class

• Entity binding Data member and Member methods in one single unit

• Data Member(Properties)

• Member Methods(Behavior)
Class
In other words class is said to be a blueprint or a template.

Why we use class Framework?


Example
To build a home the first thing we need to do is,

Blueprint

Then comes the Real House


Class Name Object
Attribute 1
Attribute 2 Heap Storage where
…… attributes are to be stored.
Method 1
Method 2
….
1 //Program Explanation
2 blade_info;
3 Class Fan motor_info;
4 { switch;
5 blade_info; regulator;
6 motor_info; These are said to be
7 switch; state(Variables)
8 regulator;
9 blade_design(); blade_design()
10 motor_design(); motor_design()
11 { These are said to be
12 …………… behavior(action)
13 }
14 switch_operate(); Fan is said to be the classname
15 speed_control(); and f is said to be the object.
16 } The classname is the user
17 Fan f; defined datatype.
18 The memory is allocated in class
19 declaration.
20
21
22
Objects
Object is a real time entity.

Multiple objects can be created for a single class.

The object can be both non-living and living objects.

Objects can be of unique specifications and characteristic behavior or


functionality.
Example
If we consider a TV
The Attributes can be display,volume
The Functionalities can be on/off and low/high.

Similarly if we consider a dog in general,


The attributes are food,breed,cost,color,reliability
The functionalities are bark.sleep,eat,walk
Static and Non-Static Members
Static Methods

Non static Methods


1 //Program 23 public void sum()
2 24 {
3 public class demo 25 int a = 90;
4 { 26 int b = 100;
5 int x = 90; 27 int c = a + b;
6 int y = 100; 28 System.out.println(c);
7 public static void main(String 29 }
8 args[]) 30
9 { 31
10 System.out.println(“HAI”); 32
11 demo obj = new demo(); 33
12 obj.sum(); 34
13 System.out.println(obj.x); 35
14 System.out.println(obj.y); 36
15 System.out.println(“Hello”); 37
16 } 38
17 39
18 40
19 41
20
21
22
1 Class A
2 {
3 public static void main(String args[])
4 {
5 byte i = 10;
6 byte j = 20;
7 byte k = i + j;
8 System.out.println(k);
9 }
10 }
11
12
13
14
15
Output
Error: incompatible types: possible lossy conversion from int to byte
1 Class A
2 {
3 public static void main(String args[])
4 {
5 int i = ‘d’;
6 System.out.println(i);
7 }
8 }
9
10
11
12
13
14
15
Output
100
1 Class A
2 {
3 public static void main(String args[])
4 {
5 int i = 028;
6 System.out.println(i);
7 }
8 }
9
10
11
12
13
14
15
Output
Error
1 Class A
2 {
3 public static void main(String args[])
4 {
5 int i = 035;
6 System.out.println(i);
7 }
8 }
9
10
11
12
13
14
15
Output
29
1 public class A
2 {
3 public static void main(String args[])
4 {
5 System.out.println(‘j’ + ’a’ + ’v’ + ’a’);
6 }
7 }
8
9
10
11
12
13
14
15
Output
418
1 public class A
2 {
3 public static void main(String args[])
4 {
5 if(true)
6 break;
7 }
8 }
9
10
11
12
13
14
15
Output
Error
THANK YOU
Operators
Topic/Course
Sub-Topic (Example: name of college)
Operators are used to perform operations on variables and values.

Topic/Course
Sub-Topic (Example: name of college) operators
• Unary operators
X=Y–1
• Binary operators

• Ternary operators
operands
Operators in Java
• Unary operators • Logical operators
• Arithmetic operators • Ternary operators
• Relational operators • Assignment operators
• Bitwise operators • instanceof operator
Unary operators

• Unary operator performs operation on only one operand.


• They are used to increment, decrement or negate a value.
Unary operators
Operator Description Example
++x(prefix)
++ Increases the value of a variable by 1
x++(postfix)
--x(prefix)
-- Decreases the value of a variable by 1
x--(postfix)
+ Used for giving positive values +x

- Used for negating the values -x

~ Negating an expression ~x

! Inverting the value of a boolean !x


What is the difference between
++x and x++ ?
1 class OperatorExample{ output
2 public static void main(String args[]){
3
4 int x=10; 10
5 System.out.println(x++); 12
6 System.out.println(++x); 12
7 System.out.println(x--); 10
10 System.out.println(--x);
11 }
12 }
1 class OperatorExample{ output
2 public static void main(String args[]){
3 int a=10;
4 int b=-10; -11
5 boolean c=true; 9
6 boolean d=false; False
7 System.out.println(~a); true
10 System.out.println(~b);
11 System.out.println(!c);
12 System.out.println(!d);
13 }
14 }
Arithmetic operators

• Arithmetic operators are used to perform common mathematical


operations like addition, subtraction etc..
Arithmetic operators
Operator Description Example
+ Adds two values x+y

- Subtracts one value from another x-y

* Multiplies two values x*y

/ Returns the division quotient x/y

% Returns the division remainder x%y


What is the difference between
/ and % ?
1 class OperatorExample{
2 public static void main(String args[]){
3 int a=10;
4 int b=5;
5 System.out.println(a+b);
6 System.out.println(a-b);
7 System.out.println(a*b);
10 System.out.println(a/b);
11 System.out.println(a%b);
12 }
13 }

output

15
5
50
2
0
Relational operators

• Relational/Comparison operators are used to compare two values.

• They return boolean result after the comparison.


Relational operators
Operator Description Example
== Returns true if left hand side is equal to right hand side x == y
Returns true if left hand side is not equal to right hand
!= x != y
side
< Returns true if left hand side is less than right hand side x<y
Returns true if left hand side is less than or equal to
<= x < =y
right hand side
Returns true if left hand side is greater than right hand
> x >=y
side
Returns true if left hand side is greater than or equal to
>= x >= y
right hand side
1 public class Test { output
2 public static void main(String args[]){
3 int a = 10;
4 int b = 20; false
5 System.out.println(a>b); true
6 System.out.println(a<b); false
7 System.out.println(a>=b); true
10 System.out.println(a<=b); false
11 System.out.println(a==b); true
12 System.out.println(a!=b);
13 }
14 }
Bitwise operators

• Bitwise operator works on bits and performs bit-by-bit operation.

• Can be applied to the integer types, long, int, short, char, and byte.
Bitwise operators
Operator Description Example
& Returns bit by bit AND of input values x&y

| Returns bit by bit OR of input values x|y

^ Returns bit by bit XOR of input values x^y

~ Returns the one’s compliment representation of the input value ~x

<< shifts the bits of the number to the left and fills 0 on voids left as a result x << 2

>> shifts the bits of the number to the right x >> 2

>>> shifts the bits of the number to the right and fills 0 on voids left as a result x >>>2
1 public class Main { output
2 public static void main(String args[]){
3 int a = 10;
4 int b = 20; 0
5 System.out.println(a&b); 30
6 System.out.println(a|b); -11
7 System.out.println(~a); 40
10 System.out.println(a<<2); 2
11 System.out.println(a>>2); 2
12 System.out.println(a>>>2);
13 }
14 }
Logical operators

• The logical operators || (conditional-OR) and && (conditional-AND)


operates on boolean expressions.

• The second condition is not evaluated if the first one is false, i.e. it has a
short-circuiting effect.
Logical operators
Operator Description Example
&& Returns true if both statements are true x < 5 && x < 10

|| Returns true if one of the statements is true x < 5 || x < 4

! Reverse the result, returns false if the result is true !(x < 5 && x < 10)
1 public class Test { output
2 public static void main(String args[]){
3 boolean a = true;
4 boolean b = false; false
5 System.out.println(a&&b); true
6 System.out.println(a||b); true
7 System.out.println(!(a && b));
10 }
11 }
Ternary operator

• Ternary/Conditional operator consists of three operands and is used to


evaluate Boolean expressions.
• Ternary operator is a shorthand version of if-else statement.
• It has three operands and hence the name ternary.
1 class OperatorExample{ output
2 public static void main(String args[]){
3 int a=2;
4 int b=5; 2
5 int min=(a<b)?a:b;
6 System.out.println(min);
7 }
10 }
Assignment operators
• Assignment operator is used to assign a value to any variable.

• In many cases assignment operator can be combined with other


operators to build a shorter version of statement called Compound
Statement.
Assignment operators
Operator Description Example
= Assigns values from right side operands to left side operand. C=A+B

+= Adds right operand to the left operand and assign the result to left operand. C += A
Subtracts right operand from the left operand and assign the result to left
-= C -= A
operand.
Multiplies right operand with the left operand and assign the result to left C *= A
*=
operand.
Divides left operand with the right operand and assign the result to left C /= A
/=
operand.
%= Takes modulus using two operands and assign the result to left operand. C %= A
Assignment operators
Operator Description Example
<<= Left shift AND assignment operator C <<= 2

>>= Right shift AND assignment operator C >>= 2

&= Bitwise AND assignment operator C &= 2

^= Bitwise exclusive OR and assignment operator C ^= 2

|= Bitwise inclusive OR and assignment operator C |= 2


What is the difference between
= and == ?
1 class OperatorExample{ output
2 public static void main(String[] args){
3 int a=10;
4 a+=3; 13
5 System.out.println(a); 9
6 a-=4; 18
7 System.out.println(a); 9
10 a*=2;
11 System.out.println(a);
12 a/=2;
13 System.out.println(a);
14 }
15 }
instanceof operators
• instanceof operator is used only for object reference variables.

• The operator checks whether the object is of a particular type (class type
or interface type).
1 public class Test { output
2 public static void main(String args[]) {
3 String name = "James";
4 boolean result = name instanceof String;
5 System.out.println( result ); true
6 }
7 }
10
11
Precedence and associativity
• Operator precedence determines which operator is evaluated first when
an expression has more than one operators.

• Associativity is used when there are two or more operators of same


precedence is present in an expression.
1 // Predict the output
2 public class A {
3 public static void main(String[] args)
4 {
5 int $_ = 5;
6 }
7 }
OUTPUT

1. Nothing
2. Error
1 // Predict the output
2 class Test {
3 public static void main(String args[]) {
4 System.out.println(10 + 20 + “Face");
5 System.out.println(“Face" + 10 + 20);
6 }
7 }
OUTPUT

1. 30Face Face30
2. 1020Face Face1020
3. 30Face Face1020
4. 1020Face Face30
1 // Predict the output
2 class Test
3 {
4 public static void main(String args[])
5 {
6 String s1 = “FACE";
7 String s2 = “FACE";
8 //System.out.println(s1==s2);
9 System.out.println("s1 == s2 is:" + s1 == s2);
10 }
}
OUTPUT

1. true
2. false
3. compiler error
4. throws an exception
THANK YOU
Write a program to perform Arithmetic operations such as addition,
subtraction, multiplication and division.

Sample Input: Sample Output:


5 7
2 3
10
1
2
1 import java.util.Scanner;
2 class Main
3
4 {
5 public static void main (String[] args)
6 {
7 Scanner in = new Scanner(System.in);
8
9 int a = in.nextInt();
10 int b = in.nextInt();
11 System.out.println(a+b);
12 System.out.println(a-b);
13
14 System.out.println(a*b);
15 System.out.println(a/b);
16 System.out.println(a%b);
17 }
18
19 }
20
21
22
There was a large ground in center of the city which is rectangular in shape. The
Corporation decides to build a cricket stadium in the area for school and college
students, But the area was used as a car parking zone. In order to protect the land
from using as an unauthorized parking zone , the corporation wanted to protect the
stadium by building a fence. In order to help the workers to build a fence, they
planned to place a thick rope around the ground. They wanted to buy only the
exact length of the rope that is needed. They also wanted to cover the entire
ground with a carpet during rainy season. They wanted to buy only the exact
quantity of carpet that is needed. They requested your help.
Can you please help them by writing a program to find the exact length of the rope
and the exact quantity of carpet that is required?
Sample Input: Sample Output:
5 22
6 30
1 import java.util.Scanner;
2 class Main
3
4 {
5 public static void main (String[] args)
6 {
7 Scanner in = new Scanner(System.in);
8
9 int l = in.nextInt();
10 int b = in.nextInt();
11 System.out.println(2*(l+b));
12 System.out.println(l*b);
13
14 }
15 }
16
17
18
19
20
21
22
Alice wanted to start a business and she was looking for a venture capitalist. Through her
friend Bob she went to a the owner of a Construction company who is looking to invest on
a emerging business. Looking after the business proposal , the owner was very much
impressed with Alice work. He wanted to invest in Alice Business. So he gives a green
signal to go ahead with the project. Alice bought Rs.X for a period of Y years from the
owner at R% interest per annum. Find the rate of interest and the total amount to be given
by Alice to the owner. The owner impressed by proper repayment of the financed amount
decides to give a special offer of 2% discount in the total interest at the end of the
settlement. Find the amount given back by Alice and also find total amount. (Note. All
rupees value should be in two decimal points).

Sample Input: Sample Output:


100 10.00
1 110.00
10 0.20
109.80
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int amt = in.nextInt();
8 int intr = in.nextInt();
9 int years = in.nextInt();
10 float a=0,b=0,c=0,d=0;
11 a=(amt*years*intr)/100;
12 b=amt + a;
13 c=(a*2)/100;
14 d=b-c;
15 System.out.printf("%.2f\n",a);
16 System.out.printf("%.2f\n",b);
17 System.out.printf("%.2f\n",c);
18 System.out.printf("%.2f\n",d);
19 }
20 }
21
22
The Training for sports day has begun and Physical education teacher has decided
to conduct some team games. The teacher wants to split the students in the Higher
Secondary into equal sized teams. In some cases, there may be some students who
are left out from teams and he wanted to use the left out students to assist him in
conducting the team games.For instance, if there are 50 students in the class and if
the class has to be divided into 7 equal sized teams, 7 students will be there in each
team and 1 student will be left out.PET asks your help to automate this team
splitting task. Can you please help him out?

Sample Input: Sample Output:


60 7
8 4
1 import java.util.Scanner;
2 class Main
3
4 {
5 public static void main (String[] args)
6 {
7 Scanner in = new Scanner(System.in);
8
9 int a = in.nextInt();
10 int b = in.nextInt();
11 System.out.println(a/b);
12 System.out.println(a%b);
13
14 }
15 }
16
17
18
19
20
21
22
A young man named d'Artagnan leaves home to travel to Paris, to join the Musketeers of
the Guard. Although D'Artagnan is not able to join this elite corps immediately, he befriends
the three most formidable musketeers of the age: Athos, Porthos and Aramis and gets
involved in affairs of the state and court.At that time, the cardinal was planning to dethrone
the king and to take the kingdom and to remove the musketeers of the guard. Since the
cardinal has spies mixed with the local public , d'Artagnan decides to send a message of his
whereabouts to the three musketeers in unique way.He gave a note to a boy which has the
following message. I am at the midpoint of the line joining the farmhouse next to the palace
and the light house. The Three musketeers were puzzled. Can you help them find out the
location of d'Artagnan?Given the coordinates of the 2 places (x1,y1) and (x2,y2), write a
program to find the location of d'Artagnan.

Sample Input: Sample Output:


2 6.0
4 9.5
10
15
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 float x1 = in.nextFloat();
8 float y1 = in.nextFloat();
9 float x2 = in.nextFloat();
10 float y2 = in.nextFloat();
11 float p1=0,p2=0;
12 p1=(x1+x2)/2;
13 p2=(y1+y2)/2;
14 System.out.printf("%.1f\n",p1);
15 System.out.printf("%.1f",p2);
16 }
17 }
18
19
20
21
22
Each Sunday, a newspaper agency sells w copies of a special edition
newspaper for Rs.x per copy. The cost to the agency of each newspaper
is Rs.y . The agency pays a fixed cost for storage, delivery and so on of
Rs.100 per Sunday. The newspaper agency wants to calculate the profit
which it obtains only on sundays. Can you please help them out by
writing a program to compute the profit given w, x and y.

Sample Input: Sample Output:


1000 900
2
1
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int a = in.nextInt();
8 int b = in.nextInt();
9 int c = in.nextInt();
10 int result=0;
11 result=((a*b)-(a*c)-100);
12 System.out.println(result);
13 }
14 }
15
16
17
18
19
20
21
22
Four kids Peter,Susan,Edmond and Lucy travel through a wardrobe to the land of
Narnia. Narnia is a fantasy world of magic with mythical beasts and talking animals.While
exploring the land of narnia Lucy found Mr.Tumnus the two legged stag ,and she followed
it, down a narrow path .She and Mr.Tumnus became friends and he offered a cup of coffee
to Lucy in his small hut.It was time for Lucy to return to her family and so she bid good bye
to Mr.Tumnus and while leaving Mr.Tumnus told that it is quite difficult to find the route
back as it was already dark.He told her to see the trees while returning back and said that
the first tree with two digits number will help her find the way and the way to go back to
her home is the sum of digits of the tree and that numbered way will lead her to the tree
next to the wardrobe where she can find the others.Lucy was already confused, so pls
help her in finding the route to her home....

Sample Input: Sample Output:


23 5
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int a = in.nextInt();
8 int sum=0,b=0,c=0;
9 b=a/10;
10 c=a%10;
11 sum=b+c;
12 System.out.println(sum);
13 }
14 }
15
16
17
18
19
20
21
22
Long ago , there was a war between the Trojans and Greeks.The Trojan and Greek
armies meet outside the walls of Troy. Seeing the bloodshed the two kings to
decide to end the battle as early as possible as both the armies suffer a lot.
The shape of the battle ground is Square. To win the war is to conquer the flag first
by the opposite army , it has been decided to place the flag post at the exact center
of the battle field. Can you please help them in placing the flag post at the exact
center? Given the coordinates of the left bottom vertex of the square ground and
the length of the side of the battle field, you need to write a program to determine
the coordinates of the centre of the ground.
[Assumption --- Length of the side is always even]

Sample Input: Sample Output:


4 8
0 4
8
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int x = in.nextInt();
8 int y = in.nextInt();
9 int l = in.nextInt();
10 int a=0,b=0;
11 a=x+(l/2);
12 b=y+(l/2);
13 System.out.println(a);
14 System.out.println(b);
15 }
16 }
17
18
19
20
21
22
d'Artagnan also joined the group of 3musketeers and now their group is calledFour
Musketeers. Meanwhile, d'Artagnan also moved to a new house in the same locality nearby
to the other three. Now the houses of Athos, Porthos and Aramis are located in the shape
of a triangle. Dinesh also has moved to a house in the same locality. When the three
musketeers asked d'Artagnan about the location of his house , he said that his house is
equidistant from the houses of the other 3. Can you please help them find out the location
of the house?Given the 3 locations {(x1,y1), (x2,y2) and (x3,y3)} of a triangle, write a
program to determine the point which is equidistant from all the 3 points.

Sample Input: Sample Output:


2 5.7
4 9.0
10
15
5
8
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int x1 = in.nextInt();
8 int y1 = in.nextInt();
9 int x2 = in.nextInt();
10 int y2 = in.nextInt();
11 int x3 = in.nextInt();
12 int y3 = in.nextInt();
13 float a=0,b=0;
14 a=(x1+x2+x3)/3.0f;
15 b=(y1+y2+y3)/3.0f;
16 System.out.printf("%.1f\n",a);
17 System.out.printf("%.1f",b);
18 }
19 }
20
21
22
Mrs.Bhulbhul is a miser to the core.She saves money even on petite
things. One dayshe heard a discount offer announced in a mall. she
wants to purchase lot of items to save her money. The discount is given
only when atleast two items are bought. Since each item has
different discount prices , she finds difficult to check the amount she has
saved. So she approaches you to device a automated discount calculator
to make her easy while billing.

Sample Input: Sample Output:


20.50 65.90
45.40 59.31
10 6.59
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 float a = in.nextFloat();
8 float b = in.nextFloat();
9 float c = in.nextFloat();
10 float x=0,y=0,y1=0,z=0;
11 x=a+b;
12 System.out.printf("%.2f\n",x);
13 y=x*c/100;
14 y1=x-y;
15 System.out.printf("%.2f\n",y1);
16 z=x*c/100;
17 System.out.printf("%.2f",z);
18 }
19 }
20
21
22
Though there have been more successful pirates, Blackbeard is one of the best-known and
widely-feared of his time . He commanded four ships and had a pirate army of 300 at the
height of his career, and defeated the famous warship, HMS “Scarborough” in sea-battle.
He was known for barreling into battle clutching two swords, with several knives and
pistols at the ready. He captured over forty merchant ships in the Caribbean, and without
flinching killed many prisoners.Blackbeard and his three pirates found a treasure of gold
coinsLong Ben too joined them. They decided to share the treasure. Blackbeard agreed to
give x % share for Long Ben. He then decided to take y % share from the remaining
treasure. His other pirates willl share equally the remaining gold coins. Write a program to
compute their share's.

Sample Input: Sample Output:


500 125
25 123
33 84
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int a = in.nextInt();
8 int b = in.nextInt();
9 int c = in.nextInt();
10 int d=0,e=0,f=0;
11 d=(a*b)/100;
12 e=((a-d)*c)/100;
13 f=(a-(d+e))/3;
14 System.out.println(d);
15 System.out.println(e);
16 System.out.println(f);
17 }
18 }
19
20
21
22
My name is Booka and I’m an alien.
I couldn't understand how you measure days, weeks, months and year.
Please make me to understand about the days, weeks, months and year.
Dear Friend,
Make Booka to understand what is meant by days,week, months and
year. Teach him about the conversion of days in to years, weeks and days
using a program.

Sample Input: Sample Output:


373 1
1
1
1 import java.util.Scanner;
2 class Main
3
4 {
5 public static void main (String[] args)
6 {
7 Scanner in = new Scanner(System.in);
8
9 int a = in.nextInt();
10 int x=0,y=0,z=0,m=0;
11 x=a/365;
12 y=a-(x*365);
13
14 z=y/7;
15 m=y-z*7;
16 System.out.println(x);
17 System.out.println(z);
18
19 System.out.println(m);
20 }
21 }
22
Having crossed the three headed dog Harry , Ron and Hermoine went through a secret trap
door in search of Sorcerer's stone .One the way they passed through a room and found that
the room has only one door opposite to them and the door through which they entered has
shut once they entered the room. The door was very large with a four digit number
imprinted on it . When Harry and Ron tried to open it by casting out spells , it didn't open ,
having tried various spells both of them got fed up and they left the task to Hermoine.
Hermoine on curiously observing the room found that a statement was written on the top of
the room.It was written as follows
" I will be always four.
“I can only be opened when you add my first and last and enter it”
“If you find a sign , you should not consider it”
Help Hermoine to break the code and open the door so that they can save the sorcerer's
stone.

Sample Input: Sample Output:


1001 2
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int a = in.nextInt();
8 int x=0,y=0;
9 x=a/1000;
10 y=a%10;
11 System.out.println(x+y);
12 }
13 }
14
15
16
17
18
19
20
21
22
Big Bunny lives in a colony , he is the only bunny in his colony who was
not able to hop. On his 5th birthday, his father bunny gifted him a Pogo
Stick as he could not jump like the other bunnies. He is so excited to play
with pogo stick. The pogo stick hops one unit per jump. He wanders
around his house jumping with pogo sticks. He wants to show the pogo
stick to his friends and decide to go using pogo sticks. Write a program
to find number of hops needed to reach his friends house. Assume that
Big Bunny's house is in the location (3,4).

Sample Input: Sample Output:


5 2
6
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int x = in.nextInt();
8 int y = in.nextInt();
9 int x1=0,y1=0;
10 x1=x-3;
11 y1=y-4;
12 if(x1 > y1)
13 System.out.print(x1);
14 else
15 System.out.print(y1);
16 }
17 }
18
19
20
21
22
Wind chill factor is the felt air temperature on exposed skin due to wind.
The wind chill temperature is always lower than the air temperature, and
is calculated as per the following formula.
wcf = 35.74 + 0.6215t + (0.4275t - 35.75) * v^0.16
Write a program to receive values of temperature and wind velocity and
calculate wind chill factor.

Sample Input: Sample Output:


35 23.92
20
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int temp = in.nextInt();
8 int vel = in.nextInt();
9 double wcf=0;
10 wcf = 35.74 + 0.6215 * temp + (0.4275*temp - 35.75) *
11 Math.pow(vel,0.16);
12 System.out.printf("%.2f",wcf);
13 }
14 }
15
16
17
18
19
20
21
22
THANK YOU
PRINTING
• There are three standard streams, all are managed by the
java.lang.System class
• Standard input--referenced by System.in
– Used for program input, typically reads input entered by the user.
• Standard output--referenced by System.out
– Used for program output, typically displays information to the user.
• Standard error--referenced by System.err
– Used to display error messages to the user.
PRINTING
The basic output statement is :
System.out.println( );

Others methods:

1. System.out.println()
2. System.out.print()
3. System.out.printf()
Let us see an example

class AssignmentOperator
{
public static void main(String[] args)
{
System.out.println("Java programming.");
}
}
Difference between print(), println() and printf()

•print() - prints string inside the quotes.

•println() - prints string inside the quotes similar like print() method. Then
the cursor moves to the beginning of the next line.

•printf() - it provides string formatting.


Guess the output
class Output
{
public static void main(String[] args)
{
System.out.println("1. println ");
System.out.println("2. println ");
System.out.print("1. print ");
System.out.print("2. print");
}
}
PRINTING VARIABLES AND LITERALS
To display integers, variables and so on, do not use quotation marks.
class Variables
{
public static void main(String[] args)
{
Double number = -10.6;
System.out.println(5);
System.out.println(number);
}
}
Print concatenated strings
You can use + operator to concatenate strings and print it.

class PrintVariables
{
public static void main(String[] args)
{
Double number = -10.6;
System.out.println("I am " + "awesome.");
System.out.println("Number = " + number);
}
}
Consider this code snippet

int a = 3;
int b = 4;
System.out.println( a + b );
System.out.println( "3" + "4" );
System.out.println( "" + a + b );
System.out.println( 3 + 4 + a + " " + b + a );
System.out.println( "Result: " + a + b );
System.out.println( "Result: " + ( a + b ) );
Printing characters
You can use + operator to concatenate strings and print it.

char a=65;
char b='A';
System.out.println(a);
System.out.println(b);
READING INPUT
READING INPUT FROM CONSOLE
In Java, there are three different ways for reading input from
the user in the command line environment(console).

1. Using Buffered Reader Class


2. Using Scanner Class
3. Using Console Class
BUFFERED READER CLASS
This method is used by wrapping the System.in (standard input
stream) in an InputStreamReader which is wrapped in a
BufferedReader, we can read input from the user in the
command line.
BUFFERED READER CLASS
import java.io.BufferedReader; // Reading data using readLine
import java.io.IOException; String name = reader.readLine();
import java.io.InputStreamReader;
public class Test // Printing the read line
{ System.out.println(name);
public static void main(String[] args) }
throws IOException }
{
//Enter data using BufferReader
BufferedReader reader =
new BufferedReader(new
InputStreamReader(System.in));
SCANNER CLASS

•This is probably the most preferred method to take input.

• The main purpose of the Scanner class is to parse primitive types and strings
using regular expressions, however it is also can be used to read input from
the user in the command line.
SCANNER CLASS
import java.util.Scanner; int a = in.nextInt();
System.out.println("You entered
class GetInputFromUser integer "+a);
{
public static void main(String args[]) float b = in.nextFloat();
{ System.out.println("You entered
// Using Scanner for Getting Input float "+b);
from User }
Scanner in = new }
Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered
string "+s);
CONSOLE CLASS

• It has been becoming a preferred way for reading user’s input from the
command line.

• In addition, it can be used for reading password-like input without echoing


the characters entered by the user; the format string syntax can also be used
(like System.out.printf()).
CONSOLE CLASS
public class Sample
{
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();

System.out.println(name);
}
}
COMMAND LINE ARGUMENTS
COMMAND LINE ARGUMENTS
The java command-line argument is an argument i.e. passed at
run time.

The arguments passed from the console can be received in the


java program and it can be used as an input.
Let us see an example

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Program 1 : Adding two integers using command line arguments

class A
Predict the output .
{
public static void main(String args[]) 9
{
System.out.println(args[0]+args[1]);
} 18
}
Program 1 : Adding two integers using command line arguments

class A{
public static void main(String args[]) Predict the output .
{
9
System.out.println(Integer.parseInt(args[0])
+Integer.parseInt(args[1]));
}
}
Program 2 : Concatenating two strings

class A
{ Predict the output .
public static void main(String args[])
Hai Hello
{
System.out.println(args[0]+args[1]);
}
}
Program 3 : Find average of your marks (5 subjects)

class A
{
public static void main(String args[]) Predict the output .
{ Input : java A 67 98 91 78 98
float avg;
avg = (args[0]+args[1]+args[2]+args[3]+args[4])/5; 86.4
System.out.println(avg);
}
}
Program 3 : Find average of your marks (5 subjects)

class A
{
public static void main(String args[]) Predict the output .
{ Input : java A 67 98 91 78 98
float avg;
avg= 86.4
(Float.valueOf(args[0])+Float.valueOf(args[1])+
Float.valueOf(args[2])+Float.valueOf(args[3])+F
loat.valueOf(args[4]))/5;
System.out.println(avg);
}
}
THANK YOU
PRINTING
• There are three standard streams, all are managed by the
java.lang.System class
• Standard input--referenced by System.in
– Used for program input, typically reads input entered by the user.
• Standard output--referenced by System.out
– Used for program output, typically displays information to the user.
• Standard error--referenced by System.err
– Used to display error messages to the user.
PRINTING
The basic output statement is :
System.out.println( );

Others methods:

1. System.out.println()
2. System.out.print()
3. System.out.printf()
Let us see an example

class AssignmentOperator
{
public static void main(String[] args)
{
System.out.println("Java programming.");
}
}
Difference between print(), println() and printf()

•print() - prints string inside the quotes.

•println() - prints string inside the quotes similar like print() method. Then
the cursor moves to the beginning of the next line.

•printf() - it provides string formatting.


Guess the output
class Output
{
public static void main(String[] args)
{
System.out.println("1. println ");
System.out.println("2. println ");
System.out.print("1. print ");
System.out.print("2. print");
}
}
PRINTING VARIABLES AND LITERALS
To display integers, variables and so on, do not use quotation marks.
class Variables
{
public static void main(String[] args)
{
Double number = -10.6;
System.out.println(5);
System.out.println(number);
}
}
Print concatenated strings
You can use + operator to concatenate strings and print it.

class PrintVariables
{
public static void main(String[] args)
{
Double number = -10.6;
System.out.println("I am " + "awesome.");
System.out.println("Number = " + number);
}
}
Consider this code snippet

int a = 3;
int b = 4;
System.out.println( a + b );
System.out.println( "3" + "4" );
System.out.println( "" + a + b );
System.out.println( 3 + 4 + a + " " + b + a );
System.out.println( "Result: " + a + b );
System.out.println( "Result: " + ( a + b ) );
Printing characters
You can use + operator to concatenate strings and print it.

char a=65;
char b='A';
System.out.println(a);
System.out.println(b);
READING INPUT
READING INPUT FROM CONSOLE
In Java, there are three different ways for reading input from
the user in the command line environment(console).

1. Using Buffered Reader Class


2. Using Scanner Class
3. Using Console Class
BUFFERED READER CLASS
This method is used by wrapping the System.in (standard input
stream) in an InputStreamReader which is wrapped in a
BufferedReader, we can read input from the user in the
command line.
BUFFERED READER CLASS
import java.io.BufferedReader; // Reading data using readLine
import java.io.IOException; String name = reader.readLine();
import java.io.InputStreamReader;
public class Test // Printing the read line
{ System.out.println(name);
public static void main(String[] args) }
throws IOException }
{
//Enter data using BufferReader
BufferedReader reader =
new BufferedReader(new
InputStreamReader(System.in));
SCANNER CLASS

•This is probably the most preferred method to take input.

• The main purpose of the Scanner class is to parse primitive types and strings
using regular expressions, however it is also can be used to read input from
the user in the command line.
SCANNER CLASS
import java.util.Scanner; int a = in.nextInt();
System.out.println("You entered
class GetInputFromUser integer "+a);
{
public static void main(String args[]) float b = in.nextFloat();
{ System.out.println("You entered
// Using Scanner for Getting Input float "+b);
from User }
Scanner in = new }
Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered
string "+s);
CONSOLE CLASS

• It has been becoming a preferred way for reading user’s input from the
command line.

• In addition, it can be used for reading password-like input without echoing


the characters entered by the user; the format string syntax can also be used
(like System.out.printf()).
CONSOLE CLASS
public class Sample
{
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();

System.out.println(name);
}
}
COMMAND LINE ARGUMENTS
COMMAND LINE ARGUMENTS
The java command-line argument is an argument i.e. passed at
run time.

The arguments passed from the console can be received in the


java program and it can be used as an input.
Let us see an example

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Program 1 : Adding two integers using command line arguments

class A
Predict the output .
{
public static void main(String args[]) 9
{
System.out.println(args[0]+args[1]);
} 18
}
Program 1 : Adding two integers using command line arguments

class A{
public static void main(String args[]) Predict the output .
{
9
System.out.println(Integer.parseInt(args[0])
+Integer.parseInt(args[1]));
}
}
Program 2 : Concatenating two strings

class A
{ Predict the output .
public static void main(String args[])
Hai Hello
{
System.out.println(args[0]+args[1]);
}
}
Program 3 : Find average of your marks (5 subjects)

class A
{
public static void main(String args[]) Predict the output .
{ Input : java A 67 98 91 78 98
float avg;
avg = (args[0]+args[1]+args[2]+args[3]+args[4])/5; 86.4
System.out.println(avg);
}
}
Program 3 : Find average of your marks (5 subjects)

class A
{
public static void main(String args[]) Predict the output .
{ Input : java A 67 98 91 78 98
float avg;
avg= 86.4
(Float.valueOf(args[0])+Float.valueOf(args[1])+
Float.valueOf(args[2])+Float.valueOf(args[3])+F
loat.valueOf(args[4]))/5;
System.out.println(avg);
}
}
THANK YOU
Topic/Course
Decision Making
Sub-Topic (Example: name of college)
Decision/Selection statements

• if
• if else
• nested if
• if else if
• switch case
Simple if

• It is used to decide whether certain statement or block of statements


will be executed or not.
Syntax:

if (condition)
{
// Executes this block if condition is true
}
1 public class IfExample { output
2 public static void main(String[] args) {
3 int age=20;
4 if(age>18){ Age is greater than 18
5 System.out.print("Age is greater than 18");
6 }
7 }
8 }
if else

• It is used for two way decision making.


• If the condition is true then the if part is executed and if the condition
is false the else part will be executed.
Syntax:

if (condition)
{
// Executes this block if condition is true
}
else
{
// Executes this block if condition is false
}
1 class IfElseDemo output
2 {
3 public static void main(String args[])
4 {
5 int i = 10; i is smaller than 15
6 if (i < 15)
7 System.out.println("i is smaller than 15");
8 else
9 System.out.println("i is greater than 15");
10 }
11 }
Nested if
• An if else statement can contain any sort of statement within it.
• It can contain another if-else statement
• An if-else may be nested within the if part.
• An if-else may be nested within the else part.
• An if-else may be nested within both parts.
Syntax:

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
1 class NestedIfDemo output
2 {
3 public static void main(String args[])
4 {
5 int i = 10; i is smaller than 15
6 if (i == 10) i is smaller than 12 too
7 {
8 if (i < 15)
9 System.out.println("i is smaller than 15");
10 if (i < 12)
11 System.out.println("i is smaller than 12 too");
12 else
13 System.out.println("i is greater than 15");
14 }
15 }
16 }
if else if

• If else if statement is a multiway branch statement.


• In if-else-if statement, as soon as the condition is met, the
corresponding set of statements get executed, rest gets ignored.
Syntax:

if (condition1)
statement1;
else if (condition2)
statement2;
.
.
else
statement n;
1 class ifelseifDemo output
2 {
3 public static void main(String args[])
4 {
5 int i = 20;
6 i is 20
7 if (i == 10)
8 System.out.println("i is 10");
9 else if (i == 15)
10 System.out.println("i is 15");
11 else if (i == 20)
12 System.out.println("i is 20");
13 else
14 System.out.println("i is not present");
15 }
16 }
switch case

• The switch statement is a multiway branch statement.


• Expression can be of type byte, short, int char or an enumeration,
String.
• The break statement is optional. If omitted, execution will continue on
into the next case.
Syntax:

switch (expression)
{
case value1: statement1;
break;
case value2: statement2;
break;
.
.
case valueN: statementN;
break;
default: statementDefault;
}
1 class SwitchCaseDemo output
2 {
3 public static void main(String args[])
4 {
5 int i = 9;
6 switch (i) i is greater than 2.
7 {
8 case 0:
9 System.out.println("i is zero.");
10 break;
11 case 1:
12 System.out.println("i is one.");
13 break;
14 case 2:
15 System.out.println("i is two.");
16 break;
17 default:
18 System.out.println("i is greater than 2.");
19 }
20 }
21 }
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int x = 10;
6 if (x) {
7 System.out.println("HELLO");
8 } else {
9 System.out.println("BYE");
10 }
11 }
12 }
13
14
15
16
17
18
19
20
21
22
OUTPUT

1. HELLO
2. Compile time error
3. Runtime Error
4. BYE
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int x = 10;
6 if (x)
7 System.out.println("HELLO");
8 System.out.println("WELCOME");
9
10 else
11 {
12 System.out.println("BYE");
13 }
14 }
15 }
OUTPUT

1. HELLO WELCOME
2. HELLO
3. BYE
4. Compile time error
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 if (true)
6 ;
7 }
8 }
OUTPUT

1. No Output
2. Compile time error
3. Runtime error
4. Runtime Exception
1 // Predict the output
2 class MainClass {
3 public static void main(String[] args)
4 {
5 int x = 10;
6 switch (x + 1 + 1) {
7 case 10:
8 System.out.println("HELLO");
9 break;
10 case 10 + 1 + 1:
11 System.out.println(“BYE");
12 break;
13 }
14 }
15 }
OUTPUT

1. Compile time error


2. BYE
3. HELLO
4. No Output
1 // Predict the output
2 public class A {
3 public static void main(String[] args)
4 {
5 if (true)
6 break;
7 }
8 }
OUTPUT

1. Nothing
2. Error
THANK YOU
Question 1
Write a program to get two integers n1 and n2 from the user and write a
program to relate 2 integers as equal to, less than or greater than..

Sample Input: Sample Output:


6 6 less than 8
8
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 int n1 = obj.nextInt(); //n1-number 1
8 int n2 = obj.nextInt(); //n2-number 2
9 if(n1 == n2)
10 System.out.println(n1+" and "+n2+" are equal");
11 else
12 {
13 if(n1>n2)
14 System.out.println(n1+" greater than "+n2);
15 else
16 System.out.println(n1+" less than "+n2);
17 }
18 }
19 }
20
21
22
Question 2
Write a program to check whether the given character is vowel or consonant or Not an
alphabet.

Sample Input : Sample Output :

e Vowel
b Consonant
$ Not an alphabet
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 char input = obj.next().charAt(0);
8 if(input >='a' && input <= 'z' || input >='A' && input <= 'Z')
9 {
10 if(input =='a'|| input =='e'||input=='i'||input=='o'||input=='u'||
11 input =='A'|| input =='E'||input=='I'||input=='O'||input=='U')
12 System.out.println("Vowel");
13 else
14 System.out.println("Consonant");
15 }
16 else
17 System.out.println("Not an alphabet");
18 }
19 }
20
21
22
Question 3
The newly appointed Vice-Chancellor of Anna University wanted to create an
automated grading system for the students to check their grade. When a student
enters a mark, the grading system displays the corresponding grade. Write a program
to solve the given problem. The grades for marks 100 - S, 90-99 is A, 80-89 is B, 70-79
is C, 60-69 is D, 50-59 is E and less than 50 is F.

Sample Input: Sample Output:


78 C
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 int mark = obj.nextInt();
8 if(mark == 100)
9 System.out.println("S");
10 else if(mark>=90 && mark <=99)
11 System.out.println("A");
12 else if(mark>=80 && mark <=89)
13 System.out.println("B");
14 else if(mark>=70 && mark <=79)
15 System.out.println("C");
16 else if(mark>=60 && mark <=69)
17 System.out.println("D");
18 else if(mark>=50 && mark <=59)
19 System.out.println("E");
20 else
21 System.out.println("F");
22 }
Question 4
A fruit seller buys a dozen of banana at Rs.X. He sells 1 banana at Rs.Y. Write a
program to determine the profit or loss in Rs. for the fruitseller.

Sample Input: Sample Output:


60 Loss : Rs.12.00
4
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 float total_cost = obj.nextFloat();//dozen of Banana total cost
8 float sold_cost = obj.nextFloat();//1 banana selling cost
9 float selling_price = 12*sold_cost;
10
11 if(total_cost > selling_price)
12 System.out.printf("Loss : Rs.%.2f",(total_cost-selling_price));
13
14 else if(total_cost < selling_price)
15 System.out.printf("profit : Rs.%.2f",(selling_price-total_cost));
16
17 else
18 System.out.println("No profit nor loss");
19 }
20 }
21
22
Question 5
Ask a user for their birth year encoded as two digits (like "62") and for the current
year, also encoded as two digits (like "99"). Write a program to find the users current
age in years.

Sample Input: Sample Output:


62 38
00
1 import java.util.Scanner;
2 class Main
3
{
4
5 public static void main(String args[])
6 {
7 Scanner obj = new Scanner(System.in);
8 int by = obj.nextInt();//by-Birth Year
9
int cy = obj.nextInt();//cy- Current Year
10
11 if(cy>by)
12 System.out.println(cy-by);
13 else
14 System.out.println(100-(by-cy));
15
}
16
17 }
18
19
20
21
22
Question 6
There are 3 labs in the CSE department are L1, L2, and L3 with a seating
capacity of x, y, and z. A single lab needs to be allocated to a class of 'n'
students. How many of the 3 labs can accommodate 'n' students?

Sample Input: Sample Output:


30 2
40
20
25
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 int x = obj.nextInt();
8 int y = obj.nextInt();
9 int z = obj.nextInt();
10 int n = obj.nextInt();
11 int count = 0;
12 if(x>=n)
13 count++;
14 if(y>=n)
15 count++;
16 if(z>=n)
17 count++;
18 System.out.println(count);
19 }
20 }
21
22
Question 7
Dora is interested so much in gardening and she plants more trees in her garden. She
plants trees in a rectangular fashion with the order of rows and columns and
numbered the trees in row-wise order. She planted the mango tree only in a 1st row,
1st column and last column. So given the tree number, your task is to find whether the
given tree is a mango tree or not? Write a program to check whether the given number
is a mango tree or not.

Sample Input: Sample Output:


5 Yes
5
11
1 import java.util.Scanner;
2 class Main
3
{
4
5 public static void main(String args[])
6 {
7 Scanner s = new Scanner(System.in);
8 int rows = s.nextInt();
9
int columns = s.nextInt();
10
11 int tree_no = s.nextInt();
12 if((tree_no<=columns)||(tree_no%columns == 0)||
13 ((tree_no - 1)%columns==0))
14 System.out.println("Yes");
15
else
16
17 System.out.println("No");
18 }
19 }
20
21
22
Question 8
Write a program to calculate the hotel tariff. The room rent is 20% high during peak
seasons [April-June, November-December]. Note: Use the switch construct.

Sample Input: Sample Output:


3 3000.00
1500
2
1 import java.util.Scanner; 23 case 4:
2 class Main 24 case 5:
3 { 25 case 6:
public static void main(String args[]) 26 case 11:
4
{ 27 case 12:
5 Scanner s = new Scanner(System.in);
6 28
int month = s.nextInt(); System.out.printf("%.2f",(rent+(0.2*rent))
7 float rent = s.nextInt();
29 day);
8 int day = s.nextInt(); 30 break;
9 switch(month) 31 default:
10 { 32 System.out.println("Invalid Input");
11 case 1: 33 break;
12 case 2: 34 }
case 3: 35 }
13
case 7: 36 }
14 case 8:
15 case 9:
16 case 10:
17 System.out.printf("%.2f",rent*day);
18 break;
19
20
21
22
Question 9
A microwave oven manufacturer recommends that when heating two items, add
50% to the heating time, and when heating three items double the heating time.
Heating more than three items at once is not recommended. Write a program to find
out the recommended heating time.

Sample Input: Sample Output:


2 7.50
5.0
1 import java.util.Scanner;
2 class Main
3 {
public static void main(String args[])
4
{
5 Scanner s = new Scanner(System.in);
6 int item = s.nextInt();
7 float ht = s.nextFloat();//ht - heating time
8 switch(item){
9 case 1:
10 System.out.println(ht);
11 break;
12 case 2:
System.out.println((ht/2)+ht);
13
break;
14 case 3:
15 System.out.println(2*ht);
16 break;
17 default:
18 System.out.println("Number of items is more");
19 break;
20 }
21 }
}
22
Question 10
Ask the customer's age and for the time on a 24-hour clock (where noon
is 12.00 and 4:30 PM is 16.30). The show timings are 10.15, 13.30, 18.00
and 22.00. The normal adult ticket price is $8.00, however, the adult
matinee price is $5.00. Adults are those over 13 years. The normal
children's ticket price is $4.00, however, the children's matinee price is
$2.00. Write a program that determines the price of a movie ticket

Sample Input: Sample Output:


16 $8.00
10.15
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[]){
5 Scanner s = new Scanner(System.in);
6 int age = s.nextInt();
7 float st = s.nextFloat();//st - Show timing
8 if(age > 13){
9 if(st >= 13.30 && st <= 17.59)//matinee show timing 13.30 to 17.59
10 System.out.println("$5.00");//evening show starts at 18.00
11 else
12 System.out.println("$8.00");
13 }
14 else
15 {
16 if(st >= 13.30 && st <= 17.59)//matinee show timing 13.30 to 17.59
17 System.out.println("$2.00");//evening show starts at 18.00
18 else
19 System.out.println("$4.00");
20 }
21 }
22 }
THANK YOU
Topic/Course
Looping
Sub-Topic (Example: name of college)
Looping

• A loop statement allows us to execute a statement or group of


statements multiple times.
Looping/Iteration statements

• for
• while
• do while
• Enhanced for
for

• It is used to iterate a part of the program several times.


• If the number of iteration is fixed, it is recommended to use for loop.
Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s) ;
}
1 class forLoopDemo output
2 {
3 public static void main(String args[])
4 { Value of x:2
5 for (int x = 2; x <= 4; x++) Value of x:3
6 System.out.println("Value of x:" + x); Value of x:4
7 }
8 }
while

• It is used to iterate a part of the program several times.


• If the number of iteration is not fixed, it is recommended to use while
loop.
Syntax:

while(condition)
{
statement(s) ;
}
1 class whileLoopDemo output
2 {
3 public static void main(String args[])
4 {
5 int x = 1; Value of x:1
6 while (x <= 4) Value of x:2
7 { Value of x:3
8 System.out.println("Value of x:" + x); Value of x:4
9 x++;
10 }
11 }
12 }
do while
• It is used to iterate a part of the program several times.
• Use do while if the number of iteration is not fixed and you must have
to execute the loop at least once.
Syntax:

do
{

statement(s) ;

} while(condition);
1 class dowhileloopDemo output
2 {
3 public static void main(String args[])
4 {
5 int x = 21;
6 do
7 { Value of x: 21
8 System.out.println("Value of x:" + x);
9 x++;
10 }while (x < 20);
11 }
12 }
What is the difference between
while and do while ?
Enhanced for

• Enhanced for loop provides a simpler way to iterate through the


elements of a collection or array.
Syntax:

for (T element:Collection obj/array)


{
statement(s) ;
}
1 public class enhancedforloop output
2 {
3 public static void main(String args[])
4 { Ron
5 String array[] = {"Ron", "Harry","Hermoine"}; Harry
6 Hermoine
7 for (String x:array)
8 {
9 System.out.println(x);
10 }
11
12 }
13 }
When to use Enhanced for loop ?
Infinite loop

• One of the most common mistakes while implementing any sort of


looping is that it may not ever exit, that is the loop runs for infinite
time.
1 public class LooppitfallsDemo output
2 {
3 public static void main(String[] args)
4 {
5 int x = 5; In the loop
6 while (x == 5) In the loop
7 { In the loop
8 System.out.println("In the loop"); In the loop
9 } In the loop
10 } In the loop
11 } In the loop
In the loop
In the loop
In the loop
In the loop
..
..
..
Jump statements

• break
• continue
• return
break

• Used to break loop or switch statement.


• When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
1 public class BreakExample { output
2 public static void main(String[] args) {
3 for(int i=1;i<=10;i++){
4 if(i==5){ 1
5 break; 2
6 } 3
7 System.out.println(i); 4
8 }
9 }
10 }
continue

• Used to continue the loop, it continues the current flow of the program
and skips the remaining code at the specified condition.
• The continue statement is used in loop control structure when you
need to jump to the next iteration of the loop immediately.
• It can be used with for loop or while loop.
1 public class ContinueExample { output
2 public static void main(String[] args) {
3 for(int i=1;i<=10;i++){
4 if(i==5){ 1
5 continue; 2
6 } 3
7 System.out.println(i); 4
8 } 6
9 } 7
10 } 8
9
10
return

• Return is used to exit from a method, with or without a value.


1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int j = 0;
6 do
7 for (int i = 0; i++ < 1 ; )
8 System.out.println(i);
9 while (j++ < 2);
10 }
11 }
OUTPUT

1. 111
2. 222
3. 333
4. error
1 // Predict the output
2 class Test {
3 static String s = "";
4 public static void main(String[] args)
5 {
6 P:
7 for (int i = 2; i < 7; i++) {
8 if (i == 3)
9 continue;
10 if (i == 5)
11 break P;
12 s = s + i;
13 }
14 System.out.println(s);
15 }
16 }
OUTPUT

1. 32
2. 23
3. 24
4. 42
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 for (int i = 0; i < 10; i++)
6 int x = 10;
7 }
8 }
9
OUTPUT

1. No Output
2. Compile time error
3. Runtime error
4. Runtime Exception
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int i = 0;
6 for (System.out.println("HI"); i < 1; i++)
7 System.out.println("HELLO");
8 }
9 }
OUTPUT

1. HI HELLO
2. No Output
3. Compile time error
4. HELLO
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 for (int i = 0;; i++)
6 System.out.println("HELLO");
7 }
8 }
OUTPUT

1. Compile time error


2. HELLO
3. HELLO(Infinitely)
4. Run-time Exception
THANK YOU
Topic/Course
Looping
Sub-Topic (Example: name of college)
Looping

• A loop statement allows us to execute a statement or group of


statements multiple times.
Looping/Iteration statements

• for
• while
• do while
• Enhanced for
for

• It is used to iterate a part of the program several times.


• If the number of iteration is fixed, it is recommended to use for loop.
Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s) ;
}
1 class forLoopDemo output
2 {
3 public static void main(String args[])
4 { Value of x:2
5 for (int x = 2; x <= 4; x++) Value of x:3
6 System.out.println("Value of x:" + x); Value of x:4
7 }
8 }
while

• It is used to iterate a part of the program several times.


• If the number of iteration is not fixed, it is recommended to use while
loop.
Syntax:

while(condition)
{
statement(s) ;
}
1 class whileLoopDemo output
2 {
3 public static void main(String args[])
4 {
5 int x = 1; Value of x:1
6 while (x <= 4) Value of x:2
7 { Value of x:3
8 System.out.println("Value of x:" + x); Value of x:4
9 x++;
10 }
11 }
12 }
do while
• It is used to iterate a part of the program several times.
• Use do while if the number of iteration is not fixed and you must have
to execute the loop at least once.
Syntax:

do
{

statement(s) ;

} while(condition);
1 class dowhileloopDemo output
2 {
3 public static void main(String args[])
4 {
5 int x = 21;
6 do
7 { Value of x: 21
8 System.out.println("Value of x:" + x);
9 x++;
10 }while (x < 20);
11 }
12 }
What is the difference between
while and do while ?
Enhanced for

• Enhanced for loop provides a simpler way to iterate through the


elements of a collection or array.
Syntax:

for (T element:Collection obj/array)


{
statement(s) ;
}
1 public class enhancedforloop output
2 {
3 public static void main(String args[])
4 { Ron
5 String array[] = {"Ron", "Harry","Hermoine"}; Harry
6 Hermoine
7 for (String x:array)
8 {
9 System.out.println(x);
10 }
11
12 }
13 }
When to use Enhanced for loop ?
Infinite loop

• One of the most common mistakes while implementing any sort of


looping is that it may not ever exit, that is the loop runs for infinite
time.
1 public class LooppitfallsDemo output
2 {
3 public static void main(String[] args)
4 {
5 int x = 5; In the loop
6 while (x == 5) In the loop
7 { In the loop
8 System.out.println("In the loop"); In the loop
9 } In the loop
10 } In the loop
11 } In the loop
In the loop
In the loop
In the loop
In the loop
..
..
..
Jump statements

• break
• continue
• return
break

• Used to break loop or switch statement.


• When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
1 public class BreakExample { output
2 public static void main(String[] args) {
3 for(int i=1;i<=10;i++){
4 if(i==5){ 1
5 break; 2
6 } 3
7 System.out.println(i); 4
8 }
9 }
10 }
continue

• Used to continue the loop, it continues the current flow of the program
and skips the remaining code at the specified condition.
• The continue statement is used in loop control structure when you
need to jump to the next iteration of the loop immediately.
• It can be used with for loop or while loop.
1 public class ContinueExample { output
2 public static void main(String[] args) {
3 for(int i=1;i<=10;i++){
4 if(i==5){ 1
5 continue; 2
6 } 3
7 System.out.println(i); 4
8 } 6
9 } 7
10 } 8
9
10
return

• Return is used to exit from a method, with or without a value.


1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int j = 0;
6 do
7 for (int i = 0; i++ < 1 ; )
8 System.out.println(i);
9 while (j++ < 2);
10 }
11 }
OUTPUT

1. 111
2. 222
3. 333
4. error
1 // Predict the output
2 class Test {
3 static String s = "";
4 public static void main(String[] args)
5 {
6 P:
7 for (int i = 2; i < 7; i++) {
8 if (i == 3)
9 continue;
10 if (i == 5)
11 break P;
12 s = s + i;
13 }
14 System.out.println(s);
15 }
16 }
OUTPUT

1. 32
2. 23
3. 24
4. 42
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 for (int i = 0; i < 10; i++)
6 int x = 10;
7 }
8 }
9
OUTPUT

1. No Output
2. Compile time error
3. Runtime error
4. Runtime Exception
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int i = 0;
6 for (System.out.println("HI"); i < 1; i++)
7 System.out.println("HELLO");
8 }
9 }
OUTPUT

1. HI HELLO
2. No Output
3. Compile time error
4. HELLO
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 for (int i = 0;; i++)
6 System.out.println("HELLO");
7 }
8 }
OUTPUT

1. Compile time error


2. HELLO
3. HELLO(Infinitely)
4. Run-time Exception
THANK YOU
Topic/Course
Looping Program - Patterns
Sub-Topic (Example: name of college)
Question 1
Write a program to generate the following patten.

Sample Input: Sample Output:


5 12345
2345
345
45
5
1 import java.util.Scanner;
2 class Pattern1
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 for(int i = 1; i<=n; i++)
9 {
10 int count = i;
11 for(int j = i; j<=n; j++)
12 {
13 System.out.print(count);
14 count++;
15 }
16 System.out.println();
17 }
18 }
19 }
20
21
22
Question 2
Write a program to generate the following patten.

Sample Input: Sample Output:


5 1
24
135
2468
13579
1 import java.util.Scanner;
2 class Pattern2
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 int k;
9 for(int i=1; i<=n; i++)
10 {
11 if(i % 2 == 1)
12 k = 1;
13 else
14 k = 2;
15 for(int j=1; j<=i; j++, k+=2)
16 {
17 System.out.print(k);
18 }
19 System.out.println();
20 }
21 }
22 }
Question 3
Write a program to generate the following patten.

Sample Input: Sample Output:


5 12345
23455
34555
45555
55555
1 import java.util.Scanner;
2 class Pattern3
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 for(int i = 1; i<=n; i++)
9 {
10 int count = i;
11 for(int j = 1; j<=n; j++)
12 {
13 System.out.print(count);
14 if(count <n)
15 count++;
16 }
17 System.out.println();
18 }
19 }
20 }
21
22
Question 4
Write a program to generate the following patten.

Sample Input: Sample Output:


5 12345
23451
34512
45123
51234
1 import java.util.Scanner;
2 class Pattern4
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 for(int i = 1; i<=n; i++)
9 {
10 int count = i;
11 for(int j = 1; j<=n; j++)
12 {
13 System.out.print(count);
14 count = count%n;
15 count++;
16 }
17 System.out.println();
18 }
19 }
20 }
21
22
Question 5
Write a program to generate the following patten.

Sample Input: Sample Output:


5 1
121
12321
1234321
123454321
1 import java.util.Scanner;
2 class Pattern6
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 for(int i=1; i<=n; i++){
9 for(int k = 1; k<=n-i ; k++) {
10 System.out.print(" ");
11 }
12 for(int j=1; j<=i; j++) {
13 System.out.print(j);
14 }
15 for(int j=i-1; j>=1; j--) {
16 System.out.print(j);
17 }
18 System.out.println();
19 }
20 }
21 }
22
Question 6
Write a program to generate the following patten.

Sample Input: Sample Output:


5 1
1 1
1 2 1
1 3 31
1 4 6 4 1
1 import java.util.Scanner;
2 class Pattern5
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 for(int line = 1; line <= n; line++) {
9 for(int space = 1; space<=n-line;space++){
10 System.out.print(" ");
11 }
12 int C=1;
13 for(int i = 1; i <= line; i++) {
14 System.out.print(C+" ");
15 C = C * (line - i) / i;
16 }
17 System.out.println();
18 }
19 }
20 }
21
22
THANK YOU
Control Structures
Topic/Course
Sub-Topic (Example: name of college)
Question 1
Write a program to generate the first n terms in the series
0.5,1.5,4.5,13.5,...

Input Format:
Input consists of a single integer which corresponds to n.

Output Format:
Output consists of the terms in the series separated by a blank space.

Sample Input: Sample Output:


5 0.5 1.5 4.5 13.5 40.5
Question 2
Write a program to generate the first n terms in the series
121,225,361,...

Input Format:
Input consists of a single integer which corresponds to n.

Output Format:
Output consists of the terms in the series separated by a blank space..

Sample Input: Sample Output:


4 121 225 361 529
Question 3
Write a program to generate the first n terms in the series.
0,2,8,14,...,34

Input Format:
Input consists of a single integer which corresponds to n.

Output Format:
Output consists of the terms in the series separated by a blank space..

Sample Input: Sample Output:


6 0 2 8 14 24 34
Question 4
Write a program to generate the first n terms in the series.
1,2.0,3.0,6.0,9.0,18.0,27.0,..

Input Format:
Input consists of a single integer which corresponds to n.

Output Format:
Output consists of the terms in the series separated by a blank space..

Sample Input: Sample Output:


8 1 2.0 3.0 6.0 9.0 18.0 27.0 54.0
Question 5
Write a program to generate the first n terms in the series.
4,5,9,18,34,...

Input Format:
Input consists of a single integer which corresponds to n.

Output Format:
Output consists of the terms in the series separated by a blank space.

Sample Input: Sample Output:


6 4 5 9 18 34 59
Question 6
Write a program to generate the given pattern.
CSK
CCSSKK
CCCSSSKKK
CCCCSSSSKKKK

Sample Input: Sample Output:


4 CSK
CCSSKK
CCCSSSKKK
CCCCSSSSKKKK
Question 7.1
The environmental eco club has discovered a new Amoeba that grows in
the order of a Fibonacci series every month. They are exhibiting their
amoeba in a national conference. They want to know the size of the
amoeba at a particular time instant. If a particular month’s index is given,
write a program to displays the amoeba’s size……???
For Example, The size of the amoeba on month 1, 2, 3, 4, 5, 6, ..will be 0,
1, 1, 2, 3, 5, 8 respectively.
Question 7.2
Input Format:
The first input containing an integer which denotes the number of the
month.

Output Format:
Print the amoeba size.
Refer the sample output for formatting.

Sample Input: Sample Output:


7 8
Question 8
a = 0, b=0, c=1 are the 1st three terms. All other terms in the Lucas
sequence are generated by
the sum of their 3 most recent predecessors.
Write a program to generate the first n terms of a Lucas Sequence.

Sample Input: Sample Output:


5 00112
Question 9
Write a program to check whether the given number is a trendy number
or not. A number is said to be a trendy number if and only if it has 3 digits
and the middle digit is divisible by 3.
Input Format:
The input containing an integer 'n' which denotes the given number

Output Format:
If the given number is a trendy number, then print "Trendy Number".
Otherwise, print "Not a Trendy Number".
Sample Input: Sample Output:
791 Trendy Number
Question 10.1
Write a program to that allows the user to enter 'n' numbers and finds the
number of positive numbers entered and the number of negative
numbers entered using a while loop.

Input Format:
Input consists of n+1 integers. The first integer corresponds to n. The next
n integers correspond to the numbers to be added. Consider 0 to be a
positive number.

Output Format:
Refer Sample Input and Output for formatting specifications.
Question 10.2
Sample Input: Sample Output:
Enter the values of n The number of positive number entered
4 is 2 and the sum is 11
5
-2
-1
6
How many times do you have to roll a pair of dice before they come up
snake eyes? You could do the experiment by rolling the dice by hand.
Write a computer program that simulates the experiment.
The program should report the number of rolls that it makes before the
dice come up snake eyes. (Note: "Snake eyes" means that both dice
show a value of 1.)
You can simulate rolling one die by choosing one of the integers 1, 2, 3,
4, 5, or 6 at random. The number you pick represents the number on the
die after it is rolled. The expression
(int)(Math.random()*6) + 1

does the computation you need to select a random integer between 1 and
6.
Which integer between 1 and 10000 has the largest number of divisors,
and how many divisors does it have? Write a program to find the
answers and print out the results. It is possible that several integers in
this range have the same, maximum number of divisors. Your program
only has to print out one of them

You might need some hints about how to find a maximum value. The
basic idea is to go through all the integers, keeping track of the largest
number of divisors that you've seen so far. Also, keep track of the
integer that had that number of divisors.
Write a program that will evaluate simple expressions such as 17 +
3 and 3.14159 * 4.7.
The expressions are to be typed in by the user. The input always
consist of a number, followed by an operator, followed by another
number.
The operators that are allowed are +, -, *, and /.
Your program should read an expression, print its value, read
another expression, print its value, and so on. The program should
end when the user enters 0 as the first number on the line.
Write a program that reads one line of input text and breaks it up into
words.
The words should be output one per line. A word is defined to be a
sequence of letters.
Any characters in the input that are not letters should be discarded. For
example, if the user inputs the line
He said, "That's not a good idea."
then the output of the program should be
He
Said
that
s
Not
a
good idea
Clue:
To test whether a character is a letter, you might use (ch >= 'a' && ch
<= 'z') || (ch >= 'A' && ch <= 'Z')
. However, this only works in English and similar languages. A better
choice is to call the standard function Character.isLetter(ch), which
returns a boolean value of true if ch is a letter and false if it is not.
This works for any Unicode character. For example, it counts an
accented e, é, as a letter.
THANK YOU
Java Inner Class

Class 1.1, 1.2, 1.3


Java Inner Classes - introduction
• Can we have another class as class
member?
• Yes, it is!
• Alternatively, it is called as NESTED
CLASSES
Java Inner Classes – syntax & example
class <class name> class STUDENT
{ {
member-1; int roll_no;
member-2; String name;
class <class name> class DATE
{ {
member-3; int dd,mm,yy;
… …
} }
} }
Java Inner Classes – instantiation
• To instantiate an inner class, we must first instantiate its enclosing
class
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

• Example
STUDENT s1 = new STUDENT();
STUDENT.DATE dob = s1.new DATE();
1 class STUDENT
2 {
3 int roll_no=25;
4 String name="KUMAR";
5 class DATE
6 {
7 int dd=25,mm=12,yy=2000;
8 }
9 }
10 class ic1
11 {
12 public static void main(String[] args)
13 {
14 STUDENT s1 = new STUDENT();
15 STUDENT.DATE dob = s1.new DATE();
16
17 System.out.println("Roll Number : "+s1.roll_no);
18 System.out.println("Name : "+s1.name);
19 System.out.println("DoB : "+dob.dd+":"+dob.mm+":"+dob.yy);
20 }
21 }
22
OUTPUT

>javac ic1.java

>java ic1
Roll Number : 25
Name : KUMAR
DoB : 25:12:2000

>
OUTPUT

Class file details are:

For main class  ic1.class

For outer class  STUDENT.class

For inner class  STUDENT$DATE.class


Java Inner Classes - purpose
• logically group classes and interfaces
• readable and maintainable
• It can access all the members of outer class including private data
members and methods
• Code Optimization - requires less code to write
Java Inner Classes - merits
1) Nested classes are used to develop more readable and maintainable
code because it logically group classes and interfaces in one place only
2) Code Optimization - requires less code to write
Java Inner Classes – types (one way)
Java Inner Classes – types (alternate way)
Java Inner Classes - types
1. Member inner class - A class created within class and outside method
2. Anonymous inner class - A class created for implementing interface or
extending class
3. Local inner class - A class created within method
4. Static nested class - A static class created within class
5. Nested interface - An interface created within class or interface
Java Inner Classes - types
1. Member inner class
• A non-static class that is created inside a class but outside a method is
called member inner class
• Example
We are creating show_result() method in member inner class that is
accessing all the members of outer class including private member
1 class STUDENT
2 {
3 int roll_no=123;
4 String name="RAMU";
5 private String result="*PASS*";
6 class RESULT
7 {
8 void show_result()
9 {
10 System.out.println("Roll Number : "+roll_no);
11 System.out.println("Name : "+name);
12 System.out.println("Result :"+result);
13 } } }
14 class mic1
15 {
16 public static void main(String[] args)
17 {
18 STUDENT s1 = new STUDENT();
19 STUDENT.RESULT r1 = s1.new RESULT();
20 r1.show_result();
21 }
22 }
OUTPUT

>javac mic1.java

>java mic1
Roll Number : 123
Name : RAMU
Result :*PASS*

>
OUTPUT

Class file details are:

For main class  mic1.class

For outer class  STUDENT.class

For inner class  STUDENT$RESULT.class


Java Inner Classes – types
1. Member inner class – internal working
• The java compiler creates two class files in case of inner class
• The class file name of inner class is "Outer$Inner.class” ie.,
“STUDENT$RESULT.class”
• If we want to instantiate inner class, we must have to create the instance
of outer class
• In such case, instance of inner class is created inside the instance of
outer class
Java Inner Classes – types
1. Member inner class – internal working
• In this case, the java compiler creates a class file named
STUDENT$RESULT.class
• The Member inner class have the reference of Outer class that is why it
can access all the data members of Outer class including private
Java Inner Classes - types
2. Anonymous inner class
• It is an inner class without a name and for which only a
single object is created
• An anonymous inner class can be useful when making an
instance of an object with certain “extras” such as
overloading/overriding methods of a class or interface,
without having to actually subclass a class
Java Inner Classes - types
2. Anonymous inner class
• It can be created by two ways:
1. Class (may be abstract or concrete) or extending
2. Interface or implementing
1 abstract class STUDENT
2 {
3 abstract void cca(); // co-curricular activities
4 abstract void eca(); // extra-curricular activities
5 }
6
7 class aic1
8 {
9 public static void main(String args[])
10 {
11 STUDENT s1 = new STUDENT()
12 {
13 void cca()
14 {
15 System.out.println("My Co-curricular Activities:
16 Seminars & Conferences");
17 }
18 void eca()
19 {
20 System.out.println("My Extra-curricular Activities:
21 Cricket & Chess");
22 }
1
2 };
3 s1.cca();
4 s1.eca();
5 }
6 }
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

>javac aic1.java

>java aic1
My Co-curricular Activities: Seminars & Conferences
My Extra-curricular Activities: Cricket & Chess

>
OUTPUT

Class file details are:

For abstract class  STUDENT.class

For main class  aic1.class

For anonymous inner class  aic1$1.class


Java Inner Classes - types
2. Anonymous inner class – extending a class (alternate)
• We know that we can create a thread by extending a
Thread class
• Suppose we need an immediate thread but we don’t
want to create a class that extend Thread class all the
time
Java Inner Classes - types
2. Anonymous inner class – extending a class (alternate)
• By the help of this type of Anonymous Inner class we can
define a ready thread as:
1
2 //Anonymous Inner class that extends a Class - Thread
3 class aic3
4 {
5 public static void main(String[] args)
6 {
7 Thread t1 = new Thread()
8 {
9 public void run()
10 {
11 System.out.println("Child Thread");
12 }
13 };
14 t1.start();
15 System.out.println("Main Thread");
16 }
17 }
18
19
20
21
22
OUTPUT

>javac aic3.java

>java aic3
Main Thread
Child Thread

>java aic3
Main Thread
Child Thread

>java aic3
Main Thread
Child Thread

>
OUTPUT

Class file details are:

For main class  aic3.class

For anonymous inner class  aic3$1.class


Java Inner Classes - types
2. Anonymous inner class – implementing an interface (alternate)
• We also know that by implementing Runnable interface
we can create a Thread
• Here we use anonymous Inner class that implements an
interface
1
2 //Anonymous Inner class that implements an interface - Thread
3 class aic4
4 {
5 public static void main(String[] args)
6 {
7 Runnable r1 = new Runnable()
8 {
9 public void run()
10 {
11 System.out.println("Child Thread");
12 }
13 };
14 Thread t1 = new Thread(r1);
15 t1.start();
16 System.out.println("Main Thread");
17 }
18 }
19
20
21
22
OUTPUT

>javac aic4.java

>java aic4
Main Thread
Child Thread

>java aic4
Main Thread
Child Thread

>java aic4
Main Thread
Child Thread

>
OUTPUT

Class file details are:

For main class  aic4.class

For anonymous inner class  aic4$1.class


Java Inner Classes - types
3. Local inner class
• A class created inside a method is called local inner class
• If we want to invoke the methods of local inner class, we
must instantiate this class inside the method
Java Inner Classes - types
3. Local inner class – class files
• When a program containing a local inner class is compiled, the
compiler generate two .class files,
• one for the outer class and
• the other for the inner class that has the reference to the outer class

• The two files are named by compiler as


• Outer.class
• Outer$1Inner.class
1 // local inner classes
2 class ARITHMETIC
3 {
4 private void getResult()
5 {
6 int a=5,b=3;
7 System.out.println("Inside inner class");
8 class CALCULATE
9 {
10 private int getSum()
11 {
12 return a+b;
13 }
14 private int getDiff()
15 {
16 return a-b;
17 }
18 private int getProduct()
19 {
20 return a*b;
21 }
22
1
2
3 private int getQuotient()
4 {
5 return a/b;
6 }
7 private int getReminder()
8 {
9 return a%b;
10 }
11 }
12 // inside method instantiating the class
13 CALCULATE calc = new CALCULATE();
14 System.out.println("a = "+a+"\tb = "+b);
15 System.out.println("Sum = "+ calc.getSum());
16 System.out.println("Difference = "+ calc.getDiff());
17 System.out.println("Product = "+ calc.getProduct());
18 System.out.println("Quotient = "+ calc.getQuotient());
19 System.out.println("Reminder = "+ calc.getReminder());
20
21 }
22
1
2
3 public static void main(String[] args)
4 {
5 ARITHMETIC arith = new ARITHMETIC();
6 arith.getResult();
7 }
8 }
9
10
11
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

>javac arithmetic.java

>java ARITHMETIC
Inside inner class
a = 5 b = 3
Sum = 8
Difference = 2
Product = 15
Quotient = 1
Reminder = 2

>

Note:
Take care of case-sensitiveness of filename while execution
OUTPUT

Class file details are:

For outer class  ARITHMETIC.class

For local inner class  ARITHMETC$1CALCULATE.class


Java Inner Classes - types
3. Local inner class - rules
• Local inner class cannot be invoked from outside the
method
• Local variable can't be private, public or protected
• Local inner classes can extend an abstract class or can
also implement an interface
Java Inner Classes - types
3. Local inner class – rules…
• The scope of local inner class is restricted to the block
they are defined in
• A local class has access to the members of its enclosing
class
Java Inner Classes - types
4. Static nested class
• Nested classes that are declared static are called static
nested classes
• A static nested class in Java is simply a class scoped within
another class
• Static nested class as such shares no relationship with
enclosing class
Java Inner Classes - types
4. Static nested class
• 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
Java Inner Classes - types
4. Static nested class
• They are accessed using the enclosing class name
• A static nested class cannot refer directly to instance
variables or methods defined in its enclosing class,
• it can use them only through an object reference
Java Inner Classes - types
4. Static nested class
• OuterClass.StaticNestedClass
• Example
• To create an object for the static nested class, use this
syntax:
• OuterClass.StaticNestedClass nestedObject = new
OuterClass.StaticNestedClass();
1
2 // static nested class
3 class Outer
4 {
5 int outer_a = 100;
6 static int outer_b = 200;
7 private static int outer_c = 300;
8
9 static class Inner
10 {
11 void show()
12 {
13 // Error:can't access outer_a var
14 //System.out.println("outer_a = " + outer_a);
15 System.out.println("static outer_b = " + outer_b);
16 System.out.println("private static outer_c = " +
17 outer_c);
18 }
19 }
20 }
21
22
1
2
3
4 public class snc1
5 {
6 public static void main(String[] args)
7 {
8 Outer.Inner sncObj = new Outer.Inner();
9 sncObj.show();
10 }
11 }
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

>javac snc1.java

>java snc1
static outer_b = 200
private static outer_c = 300

>
OUTPUT

Class file details are:

For main class  snc1.class

For outer class  Outer.class

For static inner class  Outer$Inner.class


1
2 // static nested class with static method
3 class Outer
4 {
5 int outer_a = 100;
6 static int outer_b = 200;
7 private static int outer_c = 300;
8
9 static class Inner
10 {
11 static void show()
12 {
13 System.out.println("Inside static method of static nested
14 class");
15 System.out.println("static outer_b = " + outer_b);
16 System.out.println("private static outer_c = " +
17 outer_c);
18 }
19 }
20 }
21
22
1
2
3
4 public class snc2
5 {
6 public static void main(String[] args)
7 {
8 Outer.Inner.show();
9 }
10 }
11
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

>javac snc2.java

>java snc2
Inside static method of static nested class
static outer_b = 200
private static outer_c = 300

>
OUTPUT

Class file details are:

For main class  snc2.class

For outer class  Outer.class

For static inner class  Outer$Inner.class


Java Inner Classes - types
4. Static nested class Vs Non-static nested class
• Static nested classes do not directly have access to other
members ie., non-static variables and methods of the
enclosing class because as it is static, it must access the non-
static members of its enclosing class through an object
• That is, it cannot refer to non-static members of its enclosing
class directly
Java Inner Classes - types
4. Static nested class Vs Non-static nested class
• Non-static nested classes or inner classes has access to all
members ie.,static and non-static variables and methods,
(including private) of its outer class and may refer to them
directly in the same way that other non-static members of the
outer class do
Java Inner Classes - types
4. Static nested class - application
• A static nested class in Java serves a great advantage to
namespace resolution
• This is the basic idea behind introducing static nested classes
in Java
Java Inner Classes - types
5. Nested interface
• An interface which is declared inside another interface or class is
called nested interface
• They are also known as inner/member/nested interface
• Since nested interface cannot be accessed directly, the main
purpose of using them is to resolve the namespace by grouping
related interfaces (or related interface and class) together
Java Inner Classes - types
5. Nested interface
• Nested interfaces are static by default (java compiler internally creates
public and static interface)
• We don’t have to mark them static explicitly as it would be redundant
• Nested interfaces declared inside class can take any access modifier,
however nested interface declared inside interface is public implicitly
• We can only call the nested interface by using outer class or outer interface
name followed by dot( . ), followed by the interface name
1
2
3 // interface inside a class
4 class C1
5 {
6 interface I1
7 {
8 void display();
9 }
10 }
11
12 class C2 implements C1.I1
13 {
14 public void display()
15 {
16 System.out.println("display method of interface inside a
17 class");
18 }
19 }
20
21
22
1
2
3
4 class ni1
5 {
6 public static void main(String[] args)
7 {
8 C1.I1 obj1;
9 C2 obj2 = new C2();
10 obj1=obj2;
11 obj1.display();
12 }
13 }
14
15
16
17
18
19
20
21
22
OUTPUT

>javac ni1.java

>java ni1
display method of interface inside a class

>
OUTPUT

Class file details are:

For main class  ni1.class

For outer class  C1.class

For implementation class  C2.class


1
2
3 // nested interface
4 interface I1
5 {
6 interface I2
7 {
8 void display();
9 }
10 }
11
12 class C1 implements I1.I2
13 {
14 public void display()
15 {
16 System.out.println("nested interface: display method");
17 }
18 }
19
20
21
22
1
2
3
4 class ni2
5 {
6 public static void main(String[] args)
7 {
8 // normal way
9 I1.I2 obj1 ;
10 C1 obj2 = new C1();
11 obj1=obj2;
12 obj1.display();
13
14 //upcasting way
15 I1.I2 obj = new C1();
16 obj.display();
17 }
18 }
19
20
21
22
OUTPUT

>javac ni2.java

>java ni2
nested interface: display method
nested interface: display method

>
OUTPUT

Class file details are:

For main class  ni2.class

For outer interface  I1.class

For implementation class  C1.class


Java Inner Classes - types
5. Nested interface
• Can we define a class inside the interface?
• Yes, If we define a class inside the interface, java compiler creates a static
nested class
• Example:
interface A
{
class C { … }
}
Question 1

Which is true about a method-local inner class?

A) It must be marked final B) It can be marked abstract

C) It can be marked public D) It can be marked static


SOLUTION
because a method-local inner class can be abstract

Answer : B) It can be marked abstract


Question 2
which one create an anonymous inner class from within
class B?
(program is shown in next slide)

A) A a=new A(10) { }; B) A a=new B() { };

C) B b=new A(String s) { }; D) A a=new A.B(String s) { };


1
2
3 class A
4 {
5 A(String s) { }
6 A() { }
7 }
8
9
10 class B extends A
11 {
12 B() { }
13 B(String s) {super(s);}
14 void sample() { ... }
15 }
16
17
18
19
20
21
22
SOLUTION
A a=new B() { };

because anonymous inner classes are no different from


any other class when it comes to polymorphism

Answer : B) A a=new B() { };


Question 3

Which constructs an anonymous inner class instance?

A) Runnable r = new Runnable() { };


B) Runnable r = new Runnable(public void run() { });
C) Runnable r = new Runnable { public void run(){}};
D) System.out.println(new Runnable() {public void run() { }});
SOLUTION
System.out.println(new Runnable() {public void run() { }});

It defines an anonymous inner class instance, which also


means it creates an instance of that new anonymous
class at the same time

Answer : D)
Question 4

Which statement is true about a static nested class?

A) We must have a reference to an instance of the enclosing class in order


to instantiate it
B) It does not have access to non-static members of the enclosing class
C) It's variables and methods must be static
D) It must extend the enclosing class
SOLUTION
B) It does not have access to non-static members of the
enclosing class

because a static nested class is not tied to an instance of


the enclosing class, and thus can't access the non-static
members of the class

Answer : B)
Question 5
Which is true about an anonymous inner class?

A) It can extend exactly one class and implement exactly one interface
B) It can extend exactly one class and can implement multiple interfaces
C) It can extend exactly one class or implement exactly one interface
D) It can implement multiple interfaces regardless of whether it also
extends a class
SOLUTION
C) It can extend exactly one class or implement exactly
one interface

because the syntax of an anonymous inner class allows for only


one named type after the new, and that type must be either a
single interface or a single class

Answer : C)
Question 6
Which among the following best describes a nested class?

A) Class inside a class


B) Class inside a function
C) Class inside a package
D) Class inside a structure
SOLUTION
A) Class inside a class

If a class is defined inside another class, the inner class is


termed as nested class
The inner class is local to the enclosing class
Scope matters a lot here

Answer : A) Class inside a class


Question 7
Which feature of OOP reduces the use of nested classes?

A) Encapsulation
B) Inheritance
C) Binding
D) Abstraction
SOLUTION
B) Inheritance

Using inheritance we can have the security of the class being


inherited.
The subclass can access the members of parent class.
And have more feature than a nested class being used.

Answer : B) Inheritance
Question 8
Non-static nested classes have access to _________ from
enclosing class.

A) Private members
B) Protected members
C) Public members
D) All the members
SOLUTION
D) All the members

The non-static nested class can access all the members of the
enclosing class.
All the data members and member functions can be accessed
from the nested class.
Even if the members are private, they can be accessed.

Answer : D) All the members


Question 9
Which among the following is correct advantage/disadvantage of
nested classes?

A) Makes the code more complex


B) Makes the code unreadable
C) Makes the code efficient and readable
D) Makes the code multithreaded
SOLUTION
C) Makes the code efficient and readable

The use of nested classes make the code more streamed


towards a single concept.
This allows to group the most similar and related classes
together and makes it even more efficient and readable.

Answer : C) Makes the code efficient and readable


Question 10
How to create object of the inner class?

A) OuterClass.InnerClass innerObject = outerObject.new InnerClass();


B) OuterClass.InnerClass innerObject = new InnerClass();
C) InnerClass innerObject = outerObject.new InnerClass();
D) OuterClass.InnerClass = outerObject.new InnerClass();
SOLUTION
A) OuterClass.InnerClass innerObject = outerObject.new
InnerClass();

An instance of inner class can exist only within instance of outer


class.
To instantiate the inner class, one must instantiate the outer
class first.
This can be done by the correct syntax above.

Answer : A)
Question 11
A static nested class is _____________ class in behavior that is
nested in another _________ class.

A) Top level, top level


B) Top level, low level
C) Low level, top level
D) Low level, low level
SOLUTION
A) Top level, top level

Top level class encloses the other classes or have same


preference as that of other top level classes.
Having a class inside the top level class is indirectly having a top
level class which higher degree of encapsulation.

Answer : A) Top level, top level


Question 12
If a declaration of a member in inner class has the same name as
that in the outer class, then ___________ enclosing scope.

A) Outer declaration shadows inner declaration in


B) Inner declaration shadows outer declaration in
C) Declaration gives compile time error
D) Declaration gives runtime error
SOLUTION
B) Inner declaration shadows outer declaration in

The inner class will have more preference for its local members
than those of the enclosing members.
Hence it will shadow the enclosing class members.
This process is known as shadowing.

Answer : B)
Question 13
Instance of inner class can exist only _______________
enclosing class.

A) Within
B) Outside
C) Private to
D) Public to
SOLUTION
A) Within

The class defined inside another class is local to the enclosing


class.
This means that the instance of inner class will not be valid
outside the enclosing class.
There is no restriction for instance to be private or public always.

Answer : A) Within
Question 14
A nested class can have its own static members.

A) True B) False
SOLUTION
B) False

The nested classes are associated with the object of the


enclosing class.
Hence have direct access to the members of that object.
Hence the inner class can’t have any static members of its own.
Otherwise the rule of static members would be violated using
enclosing class instance.

Answer : B) False
Question 15
How to access static nested classes?

A) OuterClass.StaticNestedClass
B) OuterClass->StaticNestedClass
C) OuterClass(StaticNestedClass)
D) OuterClass[StaticNestedClass]
SOLUTION
A) OuterClass.StaticNestedClass

Like any other member of the class, the static nested class uses
the dot operator to be accessed.
The reason behind is, the static classes can’t work with
instances, hence we use enclosing class name to access static
nested class.

Answer : A) OuterClass.StaticNestedClass
Question 16
What is the output of the following java program?

A) 15 B) 9

C) 5 D) Compilation Error
1 public class Outer
2 {
3 public static int temp1 = 1;
4 private static int temp2 = 2;
5 public int temp3 = 3;
6 private int temp4 = 4;
7 public static class Inner
8 {
9 private static int temp5 = 5;
10
11 private static int getSum()
12 {
13 return (temp1 + temp2 + temp3 + temp4 + temp5);
14 }
15 }
16 public static void main(String[] args)
17 {
18 Outer.Inner obj = new Outer.Inner();
19 System.out.println(obj.getSum());
20 }
21
22 }
SOLUTION
D) Compilation Error

static inner classes cannot access non-static fields of the


outer class

Answer : D) Compilation Error


Question 17
What is the output of the following java program?

A) Compilation Error B) Runtime Error

C) 200 D) None of the above


1 public class Outer
2 {
3 private static int data = 10;
4 private static int LocalClass()
5 {
6 class Inner
7 {
8 public int data = 20;
9 private int getData()
10 {
11 return data;
12 }
13 };
14 Inner inner = new Inner();
15 return inner.getData();
16 }
17 public static void main(String[] args)
18 {
19 System.out.println(data * LocalClass());
20 }
21 }
22
SOLUTION
C) 200

LocalClass() method defines a local inner class.


This method creates an object of class Inner and return the value of
the variable data that resides within it.

Answer : C) 200
Question 18
What is the output of the following java program?

A) Compilation Error B) Runtime Error

C) 25 D) 20
1
2 interface Anonymous
3 {
4 public int getValue();
5 }
6 public class Outer
7 {
8 private int data = 15;
9 public static void main(String[] args)
10 {
11 Anonymous inner = new Anonymous()
12 {
13 int data = 5;
14 public int getValue() { return data; }
15 public int getData() { return data; }
16 };
17 Outer outer = new Outer();
18 System.out.println(inner.getValue() + inner.getData() +
19 outer.data);
20 }
21 }
22
SOLUTION
A) Compilation Error

The method getData() is undefined in Anonymous class which


causes the compilation error.

Answer : A) Compilation Error


Question 19
What is the output of the following java program?

A) Compilation Error B) 2010

C) 1020 D) None
1
2 public class Outer {
3 private int data = 10;
4 class Inner {
5 private int data = 20;
6 private int getData() { return data; }
7 public void main(String[] args)
8 {
9 Inner inner = new Inner();
10 System.out.println(inner.getData());
11
12 }
13 }
14 private int getData() { return data; }
15 public static void main(String[] args)
16 {
17 Outer outer = new Outer();
18 Outer.Inner inner = outer.new Inner();
19 System.out.printf("%d", outer.getData());
20 inner.main(args);
21 }
22 }
SOLUTION
A) Compilation Error

Inner class defined above though, have access to the private


variable data of the Outer class, but declaring a variable data inside
an inner class makes it specific to the Inner class with no conflicts in
term of variable declaration

Answer : A) Compilation Error


Question 20
What is the output of the following java program?

A) Compilation Error B) Runtime Error

C) 100 D) None
1
2 interface OuterInterface
3 {
4 public void InnerMethod();
5 public interface InnerInterface
6 {
7 public void InnerMethod();
8 }
9 }
10 public class Outer implements OuterInterface.InnerInterface, OuterInterface
11 {
12 public void InnerMethod()
13 {
14 System.out.println(100);
15 }
16 public static void main(String[] args)
17 {
18 Outer obj = new Outer();
19 obj.InnerMethod();
20 }
21 }
22
SOLUTION
C) 100

As both the interfaces has declaration of InnerMethod(),


implementing it once works for both the InnerInterface and
OuterInterface.

Answer : C) 100
THANK YOU

You might also like