Sunteți pe pagina 1din 52

Unit 1

Introduction to Java programming

JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was
developed by James Gosling and Patrick Naughton. It is a simple programming language. Writing,
compiling and debugging a program is easy in java. It helps to create modular programs and reusable
code.

JVM

JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that
actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime Environment).

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop
Java code on one system and can expect it to run on any other Java enabled system without any
adjustment. This is all possible because of JVM.
When we compile a .java file, .class files(contains byte-code) with the same class names present
in .java file are generated by the Java compiler. This .class file goes into various steps when we run it.
These steps together describe the whole JVM

JVM Memory
Method area :In method area, all class level information like class name, immediate parent class name,
methods and variables information etc. are stored, including static variables. There is only one method
area per JVM, and it is a shared resource.
Heap area :Information of all objects is stored in heap area. There is also one Heap Area per JVM. It is
also a shared resource.
Stack area :For every thread, JVM create one run-time stack which is stored here. Every block of this
stack is called activation record/stack frame which store methods calls. All local variables of that method
are stored in their corresponding frame. After a thread terminate, it’s run-time stack will be destroyed
by JVM. It is not a shared resource.
PC Registers :Store address of current execution instruction of a thread. Obviously each thread has
separate PC Registers.
Native method stacks :For every thread, separate native stack is created. It stores native method
information.
Execution Engine
Execution engine execute the .class (bytecode). It reads the byte-code line by line, use data and
information present in various memory area and execute instructions. It can be classified in three parts
:-
• Interpreter : It interprets the bytecode line by line and then executes. The disadvantage here is
that when one method is called multiple times, every time interpretation is required.
• Just-In-Time Compiler(JIT) : It is used to increase efficiency of interpreter.It compiles the entire
bytecode and changes it to native code so whenever interpreter see repeated method calls,JIT
provide direct native code for that part so re-interpretation is not required,thus efficiency is
improved.
• Garbage Collector : It destroy un-referenced objects.For more on Garbage Collector,refer Garbage
Collector.
JAVA FEATURES :
Object Oriented

In Java, everything is an Object. Java can be easily extended since it is based on the Object model.

Platform Independent

Unlike many other programming languages including C and C++, when Java is compiled, it is not
compiled into platform specific machine, rather into platform-independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being
run on.

Simple

Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to
master.

Secure

With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.

Architecture-neutral

Java compiler generates an architecture-neutral object file format, which makes the compiled code
executable on many processors, with the presence of Java runtime system.

Portable

Being architecture-neutral and having no implementation dependent aspects of the specification makes
Java portable. The compiler in Java is written in ANSI C with a clean portability boundary, which is a
POSIX subset.

Robust
Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time error
checking and runtime checking.

Multithreaded

With Java's multithreaded feature it is possible to write programs that can perform many tasks
simultaneously. This design feature allows the developers to construct interactive applications that can
run smoothly.

Interpreted

Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The
development process is more rapid and analytical since the linking is an incremental and light-weight
process.

High Performance

With the use of Just-In-Time compilers, Java enables high performance.

Distributed

Java is designed for the distributed environment of the internet.

Dynamic

Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry an extensive amount of run-time information that can be used to
verify and resolve accesses to objects at run-time.

Creation and execution

public class Demo {

public static void main(String[] args) {

// your code goes here:

System.out.println("Hello World!");
}
}

Public: It is an Access modifier, which specifies from where and who can access the method. Making
the main() method public makes it globally available.

Static: It is a keyword which is when associated with a method, makes it a class related method.

Void: It is a keyword and used to specify that a method doesn’t return anything.
main: It is the name of Java main method. It is the identifier that the JVM looks for as the starting point
of the java program. It’s not a keyword.

String[] args: It stores Java command line arguments and is an array of type java.lang.String class. Here,
the name of the String array is args but it is not fixed and user can use any name in place of it.

Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are two types
of data types in Java:

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.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

Boolean False 1 bit


Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

Long 0L 8 byte

Float 0.0f 4 byte

Double 0.0d 8 byte

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example: Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer.
Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is
127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data
type.

Example: byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to
32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2
times smaller than an integer.
Example: short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.

Example: int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value
is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0.
The long data type is used when you need a range of values more than those provided by int.

Example: long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating
point numbers. The float data type should never be used for precise values, such as currency. Its default
value is 0.0F.

Example: float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited.
The double data type is generally used for decimal values just like float. The double data type also
should never be used for precise values, such as currency. Its default value is 0.0d.

Example: double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to
'\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example: char letterA = 'A'

Type conversion and casting


Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

• Widening Casting or implicit conversion (automatically) - converting a smaller type to a larger


type size
byte -> short -> char -> int -> long -> float -> double

• Narrowing Casting or explicit conversion (manually) - converting a larger type to a smaller size
type
double -> float -> long -> int -> char -> short -> byte

Implicit Casting

Implicit casting is done automatically when passing a smaller size type to a larger size type:

Example
public class MyClass {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}

explicit Casting

explicit casting must be done manually by placing the type in parentheses in front of the value:

Example
public class MyClass {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}
conditional statements in java
A programming language uses control statements to control the flow of execution of program based on
certain conditions..
• if
• if-else
• nested-if
• if-else-if
• switch-case
• jump – break, continue, return
These statements allow you to control the flow of your program’s execution based upon conditions
known only during run time.
• if: if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statement is executed otherwise not.
Syntax:
• if(condition)
• {
• // Statements to execute if
• // condition is true
• }
Here, condition after evaluation will be either true or false. if statement accepts boolean values –
if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will
consider the immediate one statement to be inside its block. For example,
if(condition)
statement1;
statement2;

// Here if the condition is true, if block


// will consider only statement1 to be inside
// its block.
Flow chart:

Example:
// Java program to illustrate If statement
class IfDemo
{
public static void main(String args[])
{
int i = 10;

if (i > 15)
System.out.println("10 is less than 15");

// This statement will be executed


// as if considers one statement by default
System.out.println("I am Not in if");
}
}
Output:
I am Not in if
• if-else: The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if the
condition is false. Here comes the else statement. We can use the else statement with if
statement to execute a block of code when the condition is false.
Syntax:
• if (condition)
• {
• // Executes this block if
• // condition is true
• }
• else
• {
• // Executes this block if
• // condition is false
• }

Example:

// Java program to illustrate if-else statement


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

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Output:
i is smaller than 15
• nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements
means an if statement inside an if statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.
Syntax:
• if (condition1)
• {
• // Executes when condition1 is true
• if (condition2)
• {
• // Executes when condition2 is true
• }
• }
Example:
// Java program to illustrate nested-if statement
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;

if (i == 10)
{
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");

// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
Output:
i is smaller than 15
i is smaller than 12 too
• if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed
from the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions
is true, then the final else statement will be executed.
• if (condition)
• statement;
• else if (condition)
• statement;
• .
• .
• else
• statement;

Example:
// Java program to illustrate if-else-if ladder
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;

if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Output:
i is 20
• switch-case The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
Syntax:
• switch (expression)
• {
• case value1:
• statement1;
• break;
• case value2:
• statement2;
• break;
• .
• .
• case valueN:
• statementN;
• break;
• default:
• statementDefault;
}
.
• Dulplicate case values are not allowed.
• The default statement is optional.
• The break statement is used inside the switch to terminate a statement sequence.
• The break statement is optional. If omitted, execution will continue on into the next case.

Example:
// Java program to illustrate switch-case
class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
Output:
i is greater than 2.
• jump: Java supports three jump statement: break, continue and return. These three statements
transfer control to other part of the program.
1. Break: In Java, break is majorly used for:
• Terminate a sequence in a switch statement (discussed above).
• To exit a loop.
Using break to exit a Loop
Using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
Note: Break, when used inside a set of nested loops, will only break out of the innermost
loop.

Example:
// Java program to illustrate using
// break to exit a loop
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;

System.out.println("i: " + i);


}
System.out.println("Loop complete.");
}
}
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.
2. .

Example:

// Java program to illustrate using


// continue in an if statement
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;
// If number is odd, print it
System.out.print(i + " ");
}
}
}
Output:
13579
3. Return:The return statement is used to explicitly return from a method. That is, it causes a
program control to transfer back to the caller of the method.
Example:
// Java program to illustrate using return
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");

if (t)
return;

// Compiler will bypass every statement


// after return
System.out.println("This won't execute.");
}
}
Classes and Objects in Java

Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real
life entities.

Class
A class is a user defined blueprint from which objects are created. It represents the set of properties or
methods that are common to all objects of one type. In general, class declarations can include these
components,
1. Modifiers : A class can be public or has default access
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
The class declaration component declares the name of the class along with other attributes such as the
class's superclass, and whether the class is public, final, or abstract.
At minimum, the class declaration must contain the class keyword and the name of the class that you
are defining. Thus the simplest class declaration that you can write looks like this:

class NameOfClass {
...
}
For example,.
class ImaginaryNumber {
...
}
Class names must be a legal Java identifier and, by convention, begin with a capital letter .

Object
It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an object with
other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object : dog

Objects correspond to things found in the real world. For example, a graphics program may have objects
such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping
cart”, “customer”, and “product”.
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for
each object. A single class may have any number of instances.
Example :

there are three steps when creating an object from a class −


• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The 'new' keyword is used to create the object.
• Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the
new object.
Following is an example of creating an object −

Example
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}

public static void main(String []args) {


// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it will produce the following result −

Output
Passed Name is :tommy

Method declaration and invocation:


java methods are the statements gathered together to perform a specific task. When you call any pre-
defined function like sqrt(), a series of codes related to sqrt() run in the background which is already
stored in the library. In other words, the Java method is a collection of statements or commands which
are used to run a particular task.
1. Types of Java Methods

Java Methods can be categorized into two types

• Standard Library Methods


• User-defined Methods
1.1 Standard Library

Standard Library Methods in Java are built-in methods, they are always available to use. These libraries
come along with the Java Class Library (JCL) in a .jar file with Java Virtual Machine and Java Runtime
Environment.
Some of the examples of Standard libraries are:
• print()
This method comes under java.io.PrintSteam. It prints the string which is written inside print() method
in the quotation marks
• sqrt()
This method comes under Math class. It returns the square root of a number.
1.2 User-defined

Java Method is a block of statements in or commands which are used to run a particular task and return
the result or value to the caller, it can also perform a task without returning any value. They also provide
the user to use a particular code again without retyping.
Access Specifier

An access specifier in Java defines the access type of the method, i.e. it defines in which part of the
program it can be accessed.

Java has 4 types of access modifiers


1. Public – In this type, the method is accessible in all classes in the application.
2. Protected – Here, the method is accessible in the class in which it is defined and also in its
subclasses.
3. Private – Method is accessible only in the class it is defined in.
4. Default – Method is accessible only within the same class and package in which it is defined.
Return Type

The return type defines the type of data that is returned by the method. It can return any kind of value
like integer, float, double, etc and also it returns void when nothing is returned by the method.

Method Name

A method name is used to define the name of a method, it is the same as the naming of field types with
a little difference in the convention. A method is invoked by its name.
Parameter list
The parameter list is a list with input parameters that are separated by commas, they are preceded by
their data types within closed parenthesis, and also, if there are no parameters then there is an empty
parenthesis ().
Method Body

The body of the Java method must be enclosed within braces, all the codes for the method are written
in it. All the operations are performed inside a Java method.

Method Signature

A method signature is consists of the method name and parameter list in Java i.e. number, type, and
order of parameters. Java return type and exceptions are not a part of the method signature.

Method invocation
In Java to use a method, we need to call it. A method is called according to its functionality. The method
either returns a value or return nothing(no return value). The process of calling a method is very simple.
When the program invokes any method, the control automatically gets transferred to the calling
method. It is called in any of these 3 situations

• When it completes all the statements


• An exception is thrown to it
• When it reaches a return statement
Example
1. //Program to illustrate methods in Java
2. class Addition
3. {
4. int sum = 0;
5. public int additionFunction(int operand1, int operand2)
6. {
7. // adding integer values
8. sum = operand1 + operand2;
9. return sum;
10. }
11. }
12. class AdditionProgram{
13. public static void main(String[] args){
14. // creating an instance of AdditionProgram class
15. Addition additionObj = new Addition();
16. // calling additionFunction() method to add two integer using instance created in above step.
17. int sumValue = additionObj.additionFunction(10,20);
18. System.out.println("Sum of two integer values is : "+ sumValue);
19. }
20. }
Method overloading
Method Overloading is a feature that allows a class to have more than one method having the same
name, if their argument lists are different. It is similar to constructor overloading in Java, that allows a
class to have more than one constructor having different argument lists.

Three ways to overload a method

In order to overload a method, the argument lists of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading

add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:

add(int, float)
add(float, int)
Invalid case of method overloading:
When I say argument list, I am not talking about return type of the method, for example if two methods
have same name, same parameters and have different return type, then this is not a valid method
overloading example. This will throw compilation error.

int add(int, int)


float add(int, int)
Method overloading is an example of Static Polymorphism. We will discuss polymorphism and types of
it in a separate tutorial.

Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding where
binding of method call to its definition happens at Compile time.

Method Overloading examples

As discussed in the beginning of this guide, method overloading is done by declaring same method with
different parameters. The parameters must be different in either of these: number, sequence or types
of parameters (or arguments). Lets see examples of each of these cases.

Argument list is also known as parameter list

Example 1: Overloading – Different Number of parameters in argument list

This example shows how method overloading is done by having different number of parameters

class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:

a
a 10
In the above example – method disp() is overloaded based on the number of parameters – We have two
methods with the name disp but the parameters they have are different. Both are having different
number of parameters.

Example 2: Overloading – Difference in data type of parameters

In this example, method disp() is overloaded based on the data type of parameters – We have two
methods with the name disp(), one with parameter of char type and another method with the
parameter of int type.

class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(int c)
{
System.out.println(c );
}
}

class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
Output:
a
5
Example3: Overloading – Sequence of data type of arguments

Here method disp() is overloaded based on sequence of data type of parameters – Both the methods
have different sequence of data type in argument list. First method is having argument list as (char, int)
and second is having (int, char). Since the sequence is different, the method can be overloaded without
any issues.

class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
System.out.println("I’m the second definition of method disp" );
}
}
class Sample3
{
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
Output:

I’m the first definition of method disp


I’m the second definition of method disp
Method Overloading and Type Promotion

When a data type of smaller size is promoted to the data type of bigger size than this is called type
promotion, for example: byte data type can be promoted to short, a short data type can be promoted to
int, long, double etc

Constructors

Constructor is a block of code that initializes the newly created object. A constructor resembles an
instance method in java but it’s not a method as it doesn’t have a return type. In short constructor and
method are different(More on this at the end of this guide). People often refer constructor as special
type of method in Java.
Constructor has same name as the class and looks like this in a java code.

public class MyClass{


//This is the constructor
MyClass(){
}
..
}
Note that the constructor name matches with the class name and it doesn’t have a return type.

How does a constructor work

To understand the working of constructor, lets take an example. lets say we have a class MyClass.
When we create the object of MyClass like this:

MyClass obj = new MyClass()


The new keyword here creates the object of class MyClass and invokes the constructor to initialize this
newly created object.

You may get a little lost here as I have not shown you any initialization example, lets have a look at the
code below:

A simple constructor program in java

Here we have created an object obj of class Hello and then we displayed the instance variable nameof
the object. As you can see that the output is BeginnersBook which is what we have passed to
the name during initialization in constructor. This shows that when we created the object obj the
constructor got invoked. In this example we have used this keyword, which refers to the current object,
object obj in this example.

public class Hello {


String name;
//Constructor
Hello(){
this.name = "BeginnersBook";
}
public static void main(String[] args) {
Hello obj = new Hello();
System.out.println(obj.name);
}
}
Output:

BeginnersBook
Types of Constructors

There are three types of constructors: Default, No-arg constructor and Parameterized.

Default constructor

If you do not implement any constructor in your class, Java compiler inserts a default constructor into
your code on your behalf. This constructor is known as default constructor. You would not find it in your
source code(the java file) as it would be inserted into the code during compilation and exists in .class
file. This process is shown in the diagram below:

If you implement any constructor then you no longer receive a default constructor from Java compiler.

no-arg constructor:

Constructor with no arguments is known as no-arg constructor. The signature is same as default
constructor, however body can have any code unlike default constructor where the body of the
constructor is empty.

Although you may see some people claim that that default and no-arg constructor is same but in fact
they are not, even if you write public Demo() { } in your class Demo it cannot be called default
constructor since you have written the code of it.

Example: no-arg constructor

class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
Output:
This is a no argument constructor

Parameterized constructor

Constructor with arguments(or you can say parameters) is known as Parameterized constructor.
Example: parameterized constructor

In this example we have a parameterized constructor with two parameters id and name. While creating
the objects obj1 and obj2 I have passed two arguments so that this constructor gets invoked after
creation of obj1 and obj2.

public class Employee {

int empId;
String empName;

//parameterized constructor with two parameters


Employee(int id, String name){
this.empId = id;
this.empName = name;
}
void info(){
System.out.println("Id: "+empId+" Name: "+empName);
}

public static void main(String args[]){


Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info();
}
}
Output:

Id: 10245 Name: Chaitanya


Id: 92232 Name: Negan
Example2: parameterized constructor

In this example, we have two constructors, a default constructor and a parameterized constructor.
When we do not pass any parameter while creating the object using new keyword then default
constructor is invoked, however when you pass a parameter then parameterized constructor that
matches with the passed parameters list gets invoked.

class Example2
{
private int var;
//default constructor
public Example2()
{
this.var = 10;
}
//parameterized constructor
public Example2(int num)
{
this.var = num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example2 obj = new Example2();
Example2 obj2 = new Example2(100);
System.out.println("var is: "+obj.getValue());
System.out.println("var is: "+obj2.getValue());
}
}
Output:

var is: 10
var is: 100
What if you implement only parameterized constructor in class

class Example3
{
private int var;
public Example3(int num)
{
var=num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example3 myobj = new Example3();
System.out.println("value of var is: "+myobj.getValue());
}
}
Output: It will throw a compilation error. The reason is, the statement Example3 myobj = new
Example3() is invoking a default constructor which we don’t have in our program. when you don’t
implement any constructor in your class, compiler inserts the default constructor into your code,
however when you implement any constructor (in above example I have implemented parameterized
constructor with int parameter), then you don’t receive the default constructor by compiler into your
code.
If we remove the parameterized constructor from the above code then the program would run fine,
because then compiler would insert the default constructor into your code.

Constructor Chaining

When A constructor calls another constructor of same class then this is called constructor chaining.

Super()

Whenever a child class constructor gets invoked it implicitly invokes the constructor of parent class. You
can also say that the compiler inserts a super(); statement at the beginning of child class constructor.

class MyParentClass {
MyParentClass(){
System.out.println("MyParentClass Constructor");
}
}
class MyChildClass extends MyParentClass{
MyChildClass() {
System.out.println("MyChildClass Constructor");
}
public static void main(String args[]) {
new MyChildClass();
}
}
Output:

MyParentClass Constructor
MyChildClass Constructor
Constructor Overloading

Constructor overloading is a concept of having more than one constructor with different parameters list,
in such a way so that each constructor performs a different task.

Java Copy Constructor

A copy constructor is used for copying the values of one object to another object.

class JavaExample{
String web;
JavaExample(String w){
web = w;
}

/* This is the Copy Constructor, it


* copies the values of one object
* to the another object (the object
* that invokes this constructor)
*/
JavaExample(JavaExample je){
web = je.web;
}
void disp(){
System.out.println("Website: "+web);
}

public static void main(String args[]){


JavaExample obj1 = new JavaExample("BeginnersBook");

/* Passing the object as an argument to the constructor


* This will invoke the copy constructor
*/
JavaExample obj2 = new JavaExample(obj1);
obj1.disp();
obj2.disp();
}
}
Output:

Website: BeginnersBook
Website: BeginnersBook

Garbage collection in java


When JVM starts up, it creates a heap area which is known as runtime data area. This is where all the
objects (instances of class) are stored. Since this area is limited, it is required to manage this area
efficiently by removing the objects that are no longer in use. The process of removing unused objects
from heap memory is known as Garbage collection and this is a part of memory management in Java.

Languages like C/C++ don’t support automatic garbage collection, however in java, the garbage
collection is automatic.

Now we know that the garbage collection in java is automatic. Lets see when does java performs
garbage collection.

When does java perform garbage collection?

When the object is no longer reachable:


BeginnersBook obj = new BeginnersBook();
obj = null;
Here the reference obj was pointing to the object of class BeginnersBook but since we have assigned a
null value to it, this is no longer pointing to that object, which makes the BeginnersBook object
unreachable and thus unusable. Such objects are automatically available for garbage collection in Java.

Another example is:


char[] sayhello = { 'h', 'e', 'l', 'l', 'o'};
String str = new String(sayhello);
str = null;
Here the reference str of String class was pointing to a string “hello” in the heap memory but since we
have assigned the null value to str, the object “hello” present in the heap memory is unusable.

2. When one reference is copied to another reference:

BeginnersBook obj1 = new BeginnersBook();


BeginnersBook obj2 = new BeginnersBook();
obj2 = obj1;
Here we have assigned the reference obj1 to obj2, which means the instance (object) pointed by
(referenced by) obj2 is not reachable and available for garbage collection.

How to request JVM for garbage collection

We now know that the unreachable and unusable objects are available for garbage collection but the
garbage collection process doesn’t happen instantly. Which means once the objects are ready for
garbage collection they must to have to wait for JVM to run the memory cleanup program that performs
garbage collection. However you can request to JVM for garbage collection by
calling System.gc() method (see the example below).

Garbage Collection Example in Java

In this example we are demonstrating the garbage collection by calling System.gc(). In this code we
have overridden a finalize() method. This method is invoked just before a object is destroyed by java
garbage collection process. This is the reason you would see in the output that this method has been
invoked twice.

public class JavaExample{


public static void main(String args[]){
/* Here we are intentionally assigning a null
* value to a reference so that the object becomes
* non reachable
*/
JavaExample obj=new JavaExample();
obj=null;

/* Here we are intentionally assigning reference a


* to the another reference b to make the object referenced
* by b unusable.
*/
JavaExample a = new JavaExample();
JavaExample b = new JavaExample();
b = a;
System.gc();
}
protected void finalize() throws Throwable
{
System.out.println("Garbage collection is performed by JVM");
}
}
Output:

Garbage collection is performed by JVM


Garbage collection is performed by JVM

Variable

Variable is name of reserved area allocated in memory. In other words, it is a name of memory location.
It is a combination of "vary + able" that means its value can be changed.

1. int data=50;//Here data is variable

Types of Variables

There are three types of variables in java:

o local variable
o instance variable
o static variable

1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called instance variable. It is
not declared as static.

It is called instance variable because its value is instance specific and is not shared among instances.

3) Static variable

A variable which is declared as static is called static variable. It cannot be local. You can create a single
copy of static variable and share among all the instances of the class. Memory allocation for static
variable happens only once when the class is loaded in the memory.

Example to understand the types of variables in java


1. class A{
2. int data=50;//instance variable
3. static int m=100;//static variable
4. void method(){
5. int n=90;//local variable
6. }
7. }//end of class

Java Variable Example: Add Two Numbers


1. class Simple{
2. public static void main(String[] args){
3. int a=10;
4. int b=10;
5. int c=a+b;
6. System.out.println(c);
7. }}

Output:

20

Java Variable Example: Widening


1. class Simple{
2. public static void main(String[] args){
3. int a=10;
4. float f=a;
5. System.out.println(a);
6. System.out.println(f);
7. }}
Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)


1. class Simple{
2. public static void main(String[] args){
3. float f=10.5f;
4. //int a=f;//Compile time error
5. int a=(int)f;
6. System.out.println(f);
7. System.out.println(a);
8. }}

Output:

10.5
10

Java Variable Example: Overflow


1. class Simple{
2. public static void main(String[] args){
3. //Overflow
4. int a=130;
5. byte b=(byte)a;
6. System.out.println(a);
7. System.out.println(b);
8. }}

Output:

130
-126

Java Variable Example: Adding Lower Type


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

Output:

20
Java static keyword

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

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable

If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable

1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Suppose there are 500 students in my college, now all instance data members will get memory each
time when the object is created. All students have its unique rollno and name, so instance data member
is good in such case. Here, "college" refers to the common property of all objects. If we make it static,
this field will get the memory only once.

Java static property is shared to all objects.

Example of static variable


1. //Java Program to demonstrate the use of static variable
2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24. }

Output:

111 Karan ITS


222 Aryan ITS
Program of the counter without static variable

In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object will
have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each object
will have the value 1 in the count variable.

1. //Java Program to demonstrate the use of an instance variable


2. //which get memory each time when we create an object of the class.
3. class Counter{
4. int count=0;//will get memory each time when the instance is created
5.
6. Counter(){
7. count++;//incrementing value
8. System.out.println(count);
9. }
10.
11. public static void main(String args[]){
12. //Creating objects
13. Counter c1=new Counter();
14. Counter c2=new Counter();
15. Counter c3=new Counter();
16. }
17. }

Output:

1
1
1
Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object changes the
value of the static variable, it will retain its value.

1. //Java Program to illustrate the use of static variable which


2. //is shared with all objects.
3. class Counter2{
4. static int count=0;//will get memory only once and retain its value
5.
6. Counter2(){
7. count++;//incrementing the value of static variable
8. System.out.println(count);
9. }
10.
11. public static void main(String args[]){
12. //creating objects
13. Counter2 c1=new Counter2();
14. Counter2 c2=new Counter2();
15. Counter2 c3=new Counter2();
16. }
17. }

Output:

1
2
3

2) Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Example of static method


1. //Java Program to demonstrate the use of a static method.
2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }
10. //constructor to initialize the variable
11. Student(int r, String n){
12. rollno = r;
13. name = n;
14. }
15. //method to display values
16. void display(){System.out.println(rollno+" "+name+" "+college);}
17. }
18. //Test class to create and display the values of object
19. public class TestStaticMethod{
20. public static void main(String args[]){
21. Student.change();//calling change method
22. //creating objects
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan");
25. Student s3 = new Student(333,"Sonoo");
26. //calling display method
27. s1.display();
28. s2.display();
29. s3.display();
30. }
31. }
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

this keyword in java

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the
current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity between the
instance variables and parameters, this keyword resolves the problem of ambiguity.

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}

Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we are using
this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Output:
111 ankit 5000
112 sumit 6000

If local variables(formal arguments) and instance variables are different, there is no need to use this
keyword

Arrays

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of
the same type. Or an array is the collection of same datatype with a fixed size length .
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables.

Declaring Array Variables


To use an array in a program, you must declare a variable to reference the array, and you must specify
the type of array the variable can reference. Here is the syntax for declaring an array variable −

Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.

Example
The following code examples of this syntax −
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.

Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −
• It creates an array using new dataType[arraySize].
• It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];// int [] num =new int[6]
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};//int [] num={1,2,3,4,5,6}
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0
to arrayRefVar.length-1.

Example
Following statement declares an array variable, myList, creates an array of 10 elements of double type
and assigns its reference to myList −
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the indices are
from 0 to 9.

Processing Arrays
When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.

Example
Here is a complete example showing how to create, initialize, and process arrays −
public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}

// adding all elements


double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);

// Finding the largest element


double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This will produce the following result −

Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops


JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to
traverse the complete array sequentially without using an index variable.

Example
The following code displays all the elements in the array myList −
public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
This will produce the following result −

Output
1.9
2.9
3.4
3.5

Passing Arrays to Methods


Just as you can pass primitive type values to methods, you can also pass arrays to methods. For
example, the following method displays the elements in an int array −

Example
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
You can invoke it by passing an array. For example, the following statement invokes the printArray
method to display 3, 1, 2, 6, 4, and 2 −

Example
printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method


A method may also return an array. For example, the following method returns an array that is the
reversal of another array −

Example
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {


result[j] = list[i];
}
return result;
}

The Arrays Class


The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing
arrays, and filling array elements. These methods are overloaded for all primitive types.

Two Dimensional Array in Java Programming An array, as we all know, is a collection of multiple
elements of the same data type. Arrays are normally used to store information of one particular type of
variable.
A two-dimensional entity, in general, is something that has two specific parameters. Those two
parameters are usually length and breadth since it is a physical quantity.
Similarly, a two-dimensional array is an array which technically has one row of elements, however, each
row has a bunch of elements defined by itself.
Basically, you need to define both the rows and columns and then go ahead with declaring the elements
in the respective locations or indexes.
All the methods will be explained with sample programs and suitable examples.
• Using Standard Method
• Using For Loop
• Using Scanner
• Using String


As you can see in the example given above, firstly, you need to specify the number of rows that you are
assigning with the array.

Two Dimensional – Using Standard Method

1 class TwodimensionalStandard
2 {

3 public static void main(String args[])

4 {

5 int[][] a={{10,20},{30,40}};//declaration and initialization

6 System.out.println("Two dimensional array elements are");

7 System.out.println(a[0][0]);

8 System.out.println(a[0][1]);

9 System.out.println(a[1][0]);

10 System.out.println(a[1][1]);

11 }

12 }

Output:
1 Two dimensional array elements are

2 10

3 20

4 30

5 40

Using For Loop


1. In two dimensional array represent as rows and columns.
2) To print the two-dimensional array, for loop iterates from o to i<3 for loop iterates from j=0 to j<2
print the element which is at the index a[i][j].
1 class TwodimensionalLoop

2 {

3 public static void main(String args[])

4 {

5 int[][] a={{10,20},{30,40},{50,60}};//declaration and initialization

6 System.out.println("Two dimensional array elements are");


7 for (int i = 0; i < 3; i++)

8 {

9 for (int j = 0; j < 2; j++)

10 {

11 System.out.println(a[i][j]);

12 }

13 }

14 }

15 }

Output:
1 Two dimensional array elements are

2 10

3 20

4 30

5 40

6 50

7 60

Using Scanner
1. Read the row length, column length of an array using sc.nextInt() method of Scanner class.
2) Declare the array with the dimension row, column.
3) for i=0 to i<row for j=0 to j<column sc.nextInt() reads the entered number and insert the element at
a[i][j].
1 import java.util.*;

2 class TwoDimensionalScanner

3 {

4 public static void main(String args[])

5 {

6
7 Scanner sc=new Scanner(System.in);

8 System.out.println("Enter Row length of an array : ");

9 int row=sc.nextInt();

10 System.out.println("Enter column length of an array : ");

11 int column=sc.nextInt();

12 int a[][]=new int[row][column];//declaration

13 System.out.print("Enter " + row*column + " Elements to Store in Array :\n");

14 for (int i = 0; i < row; i++)

15 {

16 for(int j = 0; j < column; j++)

17 {

18 a[i][j] = sc.nextInt();

19 }

20 }

21 System.out.print("Elements in Array are :\n");

22 for (int i = 0; i < row; i++)

23 {

24 for(int j = 0; j < column; j++)

25 {

26 System.out.println("Row ["+i+"]: Column ["+j+"] :"+a[i][j]);

27 }

28 }

29 }

30 }

Output:
1 Enter Row length of an array :

2 2
3 Enter column length of an array :

4 3

5 Enter 6 Elements to Store in Array :

6 1

7 2

8 3

9 4

10 5

11 6

12 Elements in Array are :

13 Row [0]: Column [0] :1

14 Row [0]: Column [1] :2

15 Row [0]: Column [2] :3

16 Row [1]: Column [0] :4

17 Row [1]: Column [1] :5

18 Row [1]: Column [2] :6

Two Dimensional – Using String


1. To print the elements of two-dimensional string array for i=0 to i<3 for j=0 to j<2 prints the string
element which is at the index str[i][j].
2) Here i indicates row number and j indicates column number
1 class TwoDimensionalString

2 {

3 public static void main(String[] args)

4 {

5 String[][] str = new String[][]{{"one", "two"}, {"three", "four"},{"five","six"}};

6 System.out.println("Two dimensional string array elements are :\n");

7 for (int i = 0; i < 3; i++)

8 {
9 for (int j = 0; j < 2; j++)

10 {

11 System.out.println("str["+i+"]["+j+"]:"+str[i][j]);

12 }

13 }

14 }

15 }

Output:
Output

Java

1 Two dimensional string array elements are :

3 str[0][0]:one

4 str[0][1]:two

5 str[1][0]:three

6 str[1][1]:four

7 str[2][0]:five

8 str[2][1]:six

Command line arguments in java :

The java command-line argument is an argument i.e. passed at the time of running the java program.

The arguments passed from the console can be received in the java program and it can be used as an
input.

So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.

simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one
command prompt.

1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traverse
loop.

1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc

Inner class

S-ar putea să vă placă și