Documente Academic
Documente Profesional
Documente Cultură
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
Distributed
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.
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 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.
In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
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.
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.
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
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.
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.
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.
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.
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.
• 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
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");
Example:
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;
Example:
if (t)
return;
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 :
Example
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
Output
Passed Name is :tommy
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.
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
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.
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.
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.
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.
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:
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.
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:
You may get a little lost here as I have not shown you any initialization example, lets have a look at the
code below:
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.
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.
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.
int empId;
String empName;
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.
A copy constructor is used for copying the values of one object to another object.
class JavaExample{
String web;
JavaExample(String w){
web = w;
}
Website: BeginnersBook
Website: BeginnersBook
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.
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).
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.
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.
Types of Variables
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.
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.
Output:
20
10
10.0
Output:
10.5
10
Output:
130
-126
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.
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.
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.
Output:
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.
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.
Output:
1
2
3
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.
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the
current object.
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.
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.
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.
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 {
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Example
The following code displays all the elements in the array myList −
public class TestArray {
Output
1.9
2.9
3.4
3.5
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});
Example
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
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.
1 class TwodimensionalStandard
2 {
4 {
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
2 {
4 {
8 {
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 {
5 {
6
7 Scanner sc=new Scanner(System.in);
9 int row=sc.nextInt();
11 int column=sc.nextInt();
15 {
17 {
18 a[i][j] = sc.nextInt();
19 }
20 }
23 {
25 {
27 }
28 }
29 }
30 }
Output:
1 Enter Row length of an array :
2 2
3 Enter column length of an array :
4 3
6 1
7 2
8 3
9 4
10 5
11 6
2 {
4 {
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
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
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.
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
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