Professional Documents
Culture Documents
STS Cat-1 (Java)
STS Cat-1 (Java)
STS Cat-1 (Java)
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:
• 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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introducing Java
Scenario:
Sam
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Introducing Java (Contd.)
Scenario (Contd.):
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.)
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.
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:
• 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.
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
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.
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
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
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
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
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
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Int
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
long
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Float
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
double
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Boolean
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Char
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.
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';
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';
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)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\\ backslash
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 −
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.
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.
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 :
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
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 ?
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.
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
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
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
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
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?
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
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
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
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
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
SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 16 of Resources Pvt. Ltd.
Programming in Java
MCQ
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
SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 1 of Resources Pvt. Ltd.
Programming in Java
Definition Of Object
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:
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
SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 4 of Resources Pvt. Ltd.
Programming in Java
Syntax Object Cloning
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();
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,
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
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
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 :
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:
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.
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 −
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.
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.
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 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.
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();
}}
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?
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?
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 :
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:
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.
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 −
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.
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.
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 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.
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();
}}
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?
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?
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
• Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Java if-else Statement
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.
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:
• Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Java Nested if statement
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
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
• 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.
• 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:
• 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
• 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.
//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.
• 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
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
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
• 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
• 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
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.
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 :
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 :
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 :
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
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");
}}}
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
}}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
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 }
- 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 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
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.
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.
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 :
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 −
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.
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.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
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
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.
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 −
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.
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");
}}}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
.
Control Statement Description
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 :
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.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example :
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(",");
}}}
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");
}
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
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.
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);
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
int rows = sc.nextInt();
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
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+ " ");
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
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
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
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
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
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
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
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
SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 1 of Resources Pvt. Ltd.
Programming in Java
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
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
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
SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 14 of Resources Pvt. Ltd.
Programming in Java
Final Class
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
SMART
Ver 1.0 TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training
Slide 16 of Resources Pvt. Ltd.
Programming in Java
Inner class
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
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
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
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");
}
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 ?
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;
We have to allocate memory for the array. The memory will define the number of elements that the
array can hold.
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];
In java, we can declare and allocate memory of an array in one single statement.
for example,
in Java, each element in an array are associated with a number. The number is known as an array
index.
For example,
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];
In Java, we can initialize arrays during declaration or you can initialize later in the program as per
your requirement.
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];
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;
Inside the loop, we are calculating the sum of each element. Notice the line,
Here, we are using the length attribute of the array to calculate the size of the array. We then calculate the
average using:
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
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,
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?
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)
{
class Main {
public static void main(String[] args) {
// create a 2d array
int[][] a = {{1, -2, 3}, {-4, -5, 6, 9}, {7}, };
// 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.
replace() replaces the specified old character with the specified new character
class Main {
public static void main(String[] args) {
// create a string
String greet = "Hello! World";
System.out.println("The string is: " + greet);
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);
// create strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
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) {
In the above example, we have created a string named example using the new keyword.
Here,
// create a string
String example = "This is a string";
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:
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.
// 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
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,
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,
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
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
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
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.
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
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
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
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
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
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.
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
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
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
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
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
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.
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
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
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
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
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
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.
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
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
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
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Pattern Class
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MODIFIER AND TYPE METHOD DESCRIPTION
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.
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Replacement Methods
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;
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;
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
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;
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Pattern p = Pattern.compile(REGEX);
-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";
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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
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
Regex Description
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)
}}
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
\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
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.*;
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
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)
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
String toString( )
Converts the invoking Date object into a string and returns
the result.
Character Description Example
G Era designator AD
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
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”
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
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
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;
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.
}
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:
Here are the arguments to the between() method in the Period class:
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
Answer: a
Explanation: SimpleDateFormat can be used as
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
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:
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
Answer: b
Explanation: LocalTime of joda library represents time without date.
MULTIPLE CHOICE QUESTIONS
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
Answer: a
Explanation: Java 8 provides a method called between which provides
Duration between two times.
MULTIPLE CHOICE QUESTIONS
Answer: a
Explanation: java.sql.Date is the datatype of Date stored in database.
MULTIPLE CHOICE QUESTIONS
Answer: b
Explanation: SimpleDateFormat is not thread safe. In the multithreaded
environment, we need to manage threads explicitly.
MULTIPLE CHOICE QUESTIONS
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
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
STRING ARRAYS
OUTPUT:
Volvo
BMW
Ford
Mazda
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MULTI DIMENSIONAL ARRAYS
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
TWO DIMENSIONAL ARRAYS:
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.
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Note:
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:
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?
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?
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];
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?
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Sum of an array
}
}
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];
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];
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7.Insert an element (specific position)into an array
public class test {
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. Find the maximum and minimum value of an array
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))
}
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Sum of an array
}
}
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];
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];
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
7.Insert an element (specific position)into an array
public class test {
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
8. Find the maximum and minimum value of an array
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))
}
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:
• 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.
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
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.
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MCQ Based on OOPS Concept
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
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
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
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
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Int
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
long
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Float
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
double
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Boolean
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Char
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.
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';
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';
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)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\\ backslash
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 −
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.
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.
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 :
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
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 ?
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.
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
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
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
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
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?
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:
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:
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.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The syntax of Java Inheritance
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,
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 {
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Main {
public static void main(String[] args) {
}
}
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.
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.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Why multiple inheritance is not supported in java?
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The final Keyword:
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
final class Vehicle {
...
}
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.
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
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
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:
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:
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.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The syntax of Java Inheritance
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,
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 {
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
class Main {
public static void main(String[] args) {
}
}
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.
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.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Why multiple inheritance is not supported in java?
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The final Keyword:
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
final class Vehicle {
...
}
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.
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
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
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.
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
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
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
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:
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Default:
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
same package.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
//Java program to illustrate default modifier
package p1;
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.*;
obj.display();
}
}
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
protected:
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:
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.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Ways to achieve Abstraction
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Abstract class in Java
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
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.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
abstract class Mathematics
{
// @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
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
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
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Advantages of Abstraction
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.
interface <interface_name>{
interface 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);
}
}
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
// to decrease speed
@Override
public void applyBrakes(int decrement){
}
class GFG {
Syntax:
public interface Serializable{
}
Nested Interface in Java
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");}
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.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
}
}
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
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.
class Circle{
Operation op;//aggregation
double pi=3.14;
}
Emp.java
public class Emp {
int id;
String name;
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");
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:
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:
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
1. Pseudocode
2. Algorithm
3. Flowchart
Flow Chart
Start
Input
a, b
true false
If a<b
Print a Print b
stop
Algorithm
Who is a Programmer?
Programmers are the person who writes programs in a specific computer
programming language.
Through constructor
TYPES OF PROGRAMMING
Example: Below is an example of machine language (binary) for the text "Hello
World".
● 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
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)
Each operating system has different JVM, however the output they produce
after execution of byte code is same across all operating systems.
Interview Question !!
A. Source Code
B. Byte Code
C. .obj
D. .exe
Question: 02
A. Java
B. javac
C. javadoc
D. jdk
Question: 03
A. //Some comments
B. Some comments//
C. */Some comments/*
D. /*Some comments*/
Question: 04
https://learn.codemithra.com
1. Pseudocode
2. Algorithm
3. Flowchart
Flow Chart
Start
Input
a, b
true false
If a<b
Print a Print b
stop
Algorithm
Who is a Programmer?
Programmers are the person who writes programs in a specific computer
programming language.
Through constructor
TYPES OF PROGRAMMING
Example: Below is an example of machine language (binary) for the text "Hello
World".
● 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
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)
Each operating system has different JVM, however the output they produce
after execution of byte code is same across all operating systems.
Interview Question !!
A. Source Code
B. Byte Code
C. .obj
D. .exe
Question: 02
A. Java
B. javac
C. javadoc
D. jdk
Question: 03
A. //Some comments
B. Some comments//
C. */Some comments/*
D. /*Some comments*/
Question: 04
https://learn.codemithra.com
Specifies the type and size of the values to be stored in a variable / Identifier
The char data type is used to store a single character. The character
must be surrounded by single quotes.
● 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
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
Typecasting:
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
Pre-defined methods
Example → System.out. println();
User defined methods
Example → void displayInformation(){ }
Ways to access static and non-static methods
Problem statement :
A. b1 = 3;
B. b3 = b1 * b2;
C. b3 = 10 * b1;
D. b2 = (byte) j;
Question: 03
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
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
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
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
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
A. 23.4
B. 198
A. ‘a’
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
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
Class Name
Class Variables
Class Methods
Defining a class
Heap area
Create an object
Cricketer - code snippet
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 {
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 {
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
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
e1.display();
e2.display();
e3.display();
}
}
Through constructor
“this” keyword
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
}
Through constructor
Knowledge check
}
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
DEMO
Question: 01
/* 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
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 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
System.out.println(f.process(result));
}
int process(int a) {
Question: 10
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 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
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
+= 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
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
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
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 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.
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 ('=') =
* 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;
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
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
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
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
● 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
class TemperatureConversion
{
public static void main(String arg[])
{
double fahrenheit = 98.4;
} 98.4 F is same as
} 36.888888888888886 C.
DESCRIPTION
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.
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
A. false
true
For above question correct explanation is given below.
THANK YOU
Arithmetic Operators
Increment
Decrement
Compound
Assignment Output
Question :01
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
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
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
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.
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. 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.
● Writer : Retrieves the unique PrintWriter object associated with this console.
● Reader : Retrieves the unique Reader object associated with this console.
● 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
● 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
● Flush : Flushes the console and forces any buffered output to be written
immediately .
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
● 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
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
boolean markSupported() :
Tells whether this stream supports the mark() operation, which it
does.
int read() :
Reads a single character.
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
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
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
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
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
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
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
Answer: A
QUESTION: 12
Answer: C
QUESTION: 13
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
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
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
Answer: C
QUESTION: 17
Answer: A
QUESTION: 18
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
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
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
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
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
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
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
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
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
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
Answer:
QUESTION: 32
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
A. Abc
Answer: A
B. ABC
C. Ab
D. AB
QUESTION: 34
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
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
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
Answer: C
Control statements
What you’ll learn
● 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
if(<condition>) {
//block of code
}
if statement - Example
● 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
}}
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
● for loop
● while loop
● do-while loop
For Loops
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
}
While Loop
CONDITION
TRUE FALSE
If you pass true in the while loop, it will be infinitive while loop
while(true)
{
//code to be executed
}
Infinite While Loop
dO
STATEMENT
TRUE
CONDITION
FALSE
Example
● 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
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
}
Through constructor
Code snippet
}}
Through constructor
Code snippet
● Star patterns
● Number patterns
● Character patterns
● Combination of numbers and characters
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
extends Object
● 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
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
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
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
Additional task
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..
A. If
B. For
C. Continue
D. break
Question: 02
B. Switch
C. Both
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
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
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
https://learn.codemithra.com
● 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
● 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)
{
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
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
● We can have as many nested ifs and it can go into many levels.
Classify Person
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
● 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
switch(expression)
{
case value1:
// statement1;
break;
case value2:
// statement2;
break;
default:
// statement3;
break;
}
switch Statement In Java
● Each value provided in case should be a literal value and variables are not
allowed here.
● 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
● 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
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.
● 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;
} 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
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"
a
THANK YOU
Control statements
What you’ll learn
● 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
if(<condition>) {
//block of code
}
if statement - Example
● 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
}}
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
● for loop
● while loop
● do-while loop
For Loops
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
}
While Loop
CONDITION
TRUE FALSE
If you pass true in the while loop, it will be infinitive while loop
while(true)
{
//code to be executed
}
Infinite While Loop
dO
STATEMENT
TRUE
CONDITION
FALSE
Example
● 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
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
}
Through constructor
Code snippet
}}
Through constructor
Code snippet
● Star patterns
● Number patterns
● Character patterns
● Combination of numbers and characters
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
extends Object
● 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
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
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
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
Additional task
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..
A. If
B. For
C. Continue
D. break
Question: 02
B. Switch
C. Both
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
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
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
https://learn.codemithra.com
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
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 the various below shown Pyramid pattern programs using stars
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 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
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 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");
}
}
}
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
Answer: D
QUESTION
A. Private members
B. Protected members
C. Public members
D. All members
Answer: D
QUESTION
A. Increases
B. Decreases
C. Doesn’t affect
D. Slightly decreases
Answer: A
QUESTION
A. True
B. False
Answer: B
QUESTION
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
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
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.
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());
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.
● 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
}
aabstract class C
{
abstract void method1();
int method3(double z)
{
System.out.println("I am also a concrete method");
}
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
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?
• Compile and run the java program (Assuming program is saved as Hello.java
• Web Application
• Enterprise Application
• Mobile Application
Types of Java Editions
• Java SE – Standard 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
• Package Statement
• Import Statements
• Interface Statement
• Class Definition
• Optional
• 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.
• Optional
• Similar to classes
• Modifiers • Keywords
• There may be many classes in a Java program, and only one class defines
the main method
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?
• Every variable is assigned a data type which designates the type and
quantity of value it can hold.
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.
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.
Blueprint
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
~ Negating an expression ~x
output
15
5
50
2
0
Relational operators
• 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
<< 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 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 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
! 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
+= 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
• 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.
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.
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()
•println() - prints string inside the quotes similar like print() method. Then
the cursor moves to the beginning of the next line.
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).
• 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.
System.out.println(name);
}
}
COMMAND LINE ARGUMENTS
COMMAND LINE ARGUMENTS
The java command-line argument is an argument i.e. passed at
run time.
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()
•println() - prints string inside the quotes similar like print() method. Then
the cursor moves to the beginning of the next line.
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).
• 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.
System.out.println(name);
}
}
COMMAND LINE ARGUMENTS
COMMAND LINE ARGUMENTS
The java command-line argument is an argument i.e. passed at
run time.
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
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
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 (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
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. 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..
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.
• for
• while
• do while
• Enhanced for
for
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
• break
• continue
• return
break
• 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
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
• for
• while
• do while
• Enhanced for
for
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
• break
• continue
• return
break
• 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
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
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.
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..
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..
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..
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.
Output Format:
Print the amoeba size.
Refer the sample output for formatting.
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
• 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
>javac mic1.java
>java mic1
Roll Number : 123
Name : RAMU
Result :*PASS*
>
OUTPUT
>javac aic1.java
>java aic1
My Co-curricular Activities: Seminars & Conferences
My Extra-curricular Activities: Cricket & Chess
>
OUTPUT
>javac aic3.java
>java aic3
Main Thread
Child Thread
>java aic3
Main Thread
Child Thread
>java aic3
Main Thread
Child Thread
>
OUTPUT
>javac aic4.java
>java aic4
Main Thread
Child Thread
>java aic4
Main Thread
Child Thread
>java aic4
Main Thread
Child Thread
>
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
>javac snc1.java
>java snc1
static outer_b = 200
private static outer_c = 300
>
OUTPUT
>javac snc2.java
>java snc2
Inside static method of static nested class
static outer_b = 200
private static outer_c = 300
>
OUTPUT
>javac ni1.java
>java ni1
display method of interface inside a class
>
OUTPUT
>javac ni2.java
>java ni2
nested interface: display method
nested interface: display method
>
OUTPUT
Answer : D)
Question 4
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
Answer : C)
Question 6
Which among the following best describes a nested class?
A) Encapsulation
B) Inheritance
C) Binding
D) Abstraction
SOLUTION
B) Inheritance
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 : A)
Question 11
A static nested class is _____________ class in behavior that is
nested in another _________ class.
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
Answer : A) Within
Question 14
A nested class can have its own static members.
A) True B) False
SOLUTION
B) False
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
Answer : C) 200
Question 18
What is the output of the following java program?
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
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
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
Answer : C) 100
THANK YOU