Java Fundamentals Notes
Java Fundamentals Notes
Java Fundamentals Notes
• Platform independence - Many languages are compatible with only one platform. Java was
specifically designed so that it would run on any computer, regardless if it was running Windows,
Linux, Mac, Unix or any of the other operating systems.
• Simple and easy to use - Java's creators tried to design it so code could be written efficiently and
easily.
• Multi-functional - Java can produce many applications from command-line programs to applets to
Swing windows (basically, sophisticated graphical user interfaces).
Java does have some drawbacks. Since it has automated garbage collection, it can tend to use more
memory than other similar languages. There are often implementation differences on different platforms,
which have led to Java being described as a "write once, test everywhere" system. Lastly, since it uses an
abstract "virtual machine", a generic Java program doesn't have access to the Native API's on a system
directly. None of these issues are fatal, but it can mean that Java isn't an appropriate choice for a particular
piece of software.
History of Java
a7 f4 73 5a 1b 92 7d
When the code is run by the user, it is processed by something called the Java Virtual Machine (JVM). The
JVM is essentially an interpreter for the bytecode. It goes through the bytecode and runs it. There are
different versions of the JVM that are compatible with each OS and can run the same code. There is
virtually no difference for the end-user, but this makes it a lot easier for programmers doing software
development.
Installing the Java Development Kit
Before installing the Java Development Kit (JDK), you should probably know what it is. It is distributed
by Oracle. It contains the core libraries and compiler required to develop Java. The JDK should not be
confused with the JRE (Java Runtime Environment). The JRE is a JVM for running, as opposed to
compiling, Java programs.
Note on Editions
The JDK comes in three editions.
• Java Standard Edition (JSE) – This version is the basic platform for Java. The course will focus on this
edition.
• Java Enterprise Edition (JEE) – This edition is mainly for developing and running distributed multitier
architecture Java applications, based largely on modular software components running on an
application server. We will not be covering this version in the course.
• Java Micro Edition (JME) – This edition is primarily for developing programs to run on consumer
appliances, such as PDAs and cell phones.
Configuring Variables
Before writing code, it is recommended that you set the Path variable on your system so you can compile
your code more easily.
• From the Control Panel, double click "System" (System and Maintenance in Vista)
• For Windows 7 or Vista, click on "System," "Advanced System Settings" on the left, and then on
"Environment Variables."
• For XP and 2000, click on the "Advanced" tab and click on "Environment Variables" For NT, click on
the "Environment" tab.
• Select the Path variable and click "Edit"
• Add the path to the bin directory of where Java is installed on your hard drive. It should probably be:
C:\Program Files\Java\jdk1.6.0_20\bin unless you changed it during installation.
• Click OK
"Hello World"
Anytime you learn a computer programming language, it is tradition that the first program you write
should be to make your computer say, "Hello World". This is a small feat, but is a good opportunity to
make sure that you installed the JDK properly.
The Java compiler reads basic text files. Open up a text editor like Notepad (Don't use a complex program
like Word for this). Type this code, remembering that Java is case-sensitive:
Save this file as HelloWorld.java. Start your system's command line and navigate to the folder that you
saved HelloWorld.java to. Type javac HelloWorld.java. This runs the java compiler, javac, and creates a
class file, which contains the bytecode for the application. Next type java -cp . HelloWorld. This runs the
class file that was just created by the compiler. Your console should print:
Hello World!
Syntax and Comments
As mentioned above, Java is case-sensitive, meaning that if a variable name is "day" it cannot be referred
to as "Day" later in the program. In addition, semicolons must end each statement in the code.
Programmers also use comments to insert statements into their code that the computer ignores. Comments
can be used to help explain code so that other programmers can understand it or the original writer of the
code can remember what their code does. Java has several types of comments.
a. public: This is access modifier keyword which tells compiler access to class.
Various values of access modifiers can be public, protected,private or default (no
value).
b. class: This keyword used to declare a class. Name of class (HelloWorld) followed
by this keyword.
3. Comments section:
a. Line comments: It starts with two forward slashes (//) and continues to the end of
the current line. Line comments do not require an ending symbol.
b. Block comments start with a forward slash and an asterisk (/*) and end with an
asterisk and a forward slash (*/).Block comments can also extend across as many lines
as needed.
b. static: static is a reserved keyword which means that a method is accessible and
usable even though no objects of the class exist.
c. void: This keyword declares nothing would be returned from the method. The
method can return any primitive or object.
c. println: It is utility method name which is used to send any String to the console.
d. “Hello World from Java”: It is String literal set as argument to println method.
Translation process
All of the translation process is done when you compile a Java program. This is no different than
compiling a C++ program or any other compiled language. The biggest difference is that this
translation is targeted to the Java Byte Code language rather than assembly or machine language.
The Byte Code undergoes its own translation process (including many of the same stages) when
the program is run
Java Output
You can simply use System.out.println(), System.out.print() or System.out.printf() to send output to
standard output (screen).
System is a class and out is a public static field which accepts output data. Don't worry if you
don't understand it. Classes, public, and static will be discussed in later chapters.
1. class AssignmentOperator {
2. public static void main(String[] args) {
3.
4. System.out.println("Java programming is interesting.");
5. }
6. }
1. println
2. println
1. print 2. print
Java Input
There are several ways to get input from the user in Java. You will learn to get input by
using Scanner object in this article.
For that, you need to import Scanner class using:
import java.util.Scanner;
Then, we will create an object of Scanner class which will be used to get input from the user.
Enter an integer: 23
You entered 23
Here, input object of Scanner class is created. Then, the nextInt() method of the Scannerclass is
used to get integer input from the user.
To get long, float, double and String input from the user, you can
use nextLong(), nextFloat(), nextDouble() and next() methods respectively.
Example 6: Get float, double and String Input
1. import java.util.Scanner;
2.
3. class Input {
4. public static void main(String[] args) {
5.
6. Scanner input = new Scanner(System.in);
7.
8. // Getting float input
9. System.out.print("Enter float: ");
10. float myFloat = input.nextFloat();
11. System.out.println("Float entered = " + myFloat);
12.
13. // Getting double input
14. System.out.print("Enter double: ");
15. double myDouble = input.nextDouble();
16. System.out.println("Double entered = " + myDouble);
17.
18. // Getting String input
19. System.out.print("Enter text: ");
20. String myString = input.next();
21. System.out.println("Text entered = " + myString);
22. }
23. }
Constants in Java
A constant is a variable which cannot have its value changed after declaration. It uses the
'final' keyword.
Syntax
modifier final dataType variableName = value; //global constant
Constants are very popular with classes. Because the value of a constant doesn't change
between created objects, it is usually declared static. The static keyword changes the way the
value is accessed: the value of the constant isn't accessed using the object, but with the class
name itself.
Example
public final double PI = 3.14; //global constant, outside of a class
Java Variables
A variable is a container which holds the value while the java program is executed. A variable is assigned with a
datatype.
Variable is a name of memory location. There are three types of variables in java: local, instance and static.
There are two types of data types in java: primitive and non-primitive.
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.
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.
Confusing DIVISIONS
Be careful when performing integer division. When dividing an integer
by an integer, the answer will be an integer (not rounded).
When an operation involves two types (as the mixed division shown above),
the smaller type is converted to the larger type. In the case above, the integer
5 was converted to a double type before the division occurred.
Order of Operations
The normal rules you learned in mathematics for order of operations also
apply to programming. The answer to 2 + 7 * 3 is 23 (not 27). In math
you learned to use PEMDAS (Please Excuse My Dear Aunt Sally) for
determining order of operations.
Primitive Type:
• Includes Byte, Short, Int, Long, Float, Double, Boolean, Char.
• For primitive type of variable, on visiting the memory location, you will find the value of variable.
• During assignment, primitive value is copied in this case.
Example:
Private int age=20;
Reference type:
• Includes any insatiable class or arrays.
• In this case when we visit memory location, we will find an address pointing to another memory location
which stores the value
• During comparison in this case, addresses are checked to assure whether t they point to same object.
• Returns address.
• They are defined by the programmer and memory allocation is done using new operator.
Example:
Account a = new Account();
What is OOPS?
Object Oriented Programming is a programming concept that works on the
principle that objects are the most important part of your program. It allows users
create the objects that they want and then create methods to handle those objects.
Manipulating these objects to get results is the goal of Object Oriented
Programming.
2) Object
3) Inheritance
Inheritance is an OOPS concept in which one object acquires the properties and
behaviors of the parent object. It’s creating a parent-child relationship between two
classes. It offers robust and natural mechanism for organizing and structure of any
software.
4) Polymorphism
5) Abstraction
6) Encapsulation
Encapsulation is an OOP technique of wrapping the data and code. In this OOPS
concept, the variables of a class are always hidden from other classes. It can only
be accessed using the methods of their current class. For example - in school, a
student cannot exist without a class.
7) Association
8) Aggregation
In this technique, all objects have their separate lifecycle. However, there is
ownership such that child object can’t belong to another parent object. For example
consider class/objects department and teacher. Here, a single teacher can’t belong
to multiple departments, but even if we delete the department, the teacher object
will never be destroyed.
9) Composition
Advantages of OOPS:
• OOP offers easy to understand and a clear modular structure for programs.
• Objects created for Object-Oriented Programs can be reused in other
programs. Thus it saves significant development cost.
• Large programs are difficult to write, but if the development and designing
team follow OOPS concept then they can better design with minimum
flaws.
• It also enhances program modularity because every object exists
independently.
Comparison of OOPS with other programming styles
with help of an Example
Let's understand with example how OOPs is different than other programming
approaches.
Abstract Class
A class which is declared “abstract” is called as an abstract class. It can have
abstract methods as well as concrete methods. A normal class cannot have abstract
methods.
Abstract Method
A method without a body is known as an Abstract Method. It must be declared in
an abstract class. The abstract method will never be final because the abstract class
must implement all the abstract methods.
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on
the data (methods) together as a single unit. In encapsulation, the variables of a class will be
hidden from other classes, and can be accessed only through the methods of their current
class. Therefore, it is also known as data hiding.
• Provide public setter and getter methods to modify and view the variables values.
Example
Following is an example that demonstrates how to achieve Encapsulation in Java −
return age;
return name;
return idNum;
age = newAge;
name = newName;
idNum = newId;
The public setXXX() and getXXX() methods are the access points of the instance variables
of the EncapTest class. Normally, these methods are referred as getters and setters.
Therefore, any class that wants to access the variables should access them through these
getters and setters.
The variables of the EncapTest class can be accessed using the following program −
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
Output
Name : James Age : 20
Benefits of Encapsulation
• The fields of a class can be made read-only or write-only.
• A class can have total control over what is stored in its fields.
Abstraction Encapsulation
class Bike
{
this.color = color;
this.wheels = wheels;
Step 2: Second we create a class Honda which extends the above class Bike.
Here Honda class uses HondaEngine class object start() method via composition.
Now we can say that Honda class HAS-A HondaEngine:
e.start();
}
Step 3: Third we create a class HondaEngine through which we uses this class object
in above class Honda:
class HondaEngine
class CompositionDemo
{
public static void main(String[] args)
{
Honda h = new Honda();
h.setColor("Black");
h.setwheels(2);
h.bikeFeatures();
h.setStart();
}
Output:
Importance of Composition:
• In composition we can control the visibility of other object to client classes and
reuse only what we need.
• Composition allows creation of back-end class when it is needed.
Example
Create a class called "MyClass" with two attributes: x and y:
Accessing Attributes
You can access attributes by creating an object of the class, and by using the dot syntax ( .):
The following example will create an object of the MyClass class, with the name myObj. We
use the x attribute on the object to print its value:
Example
Create an object called "myObj" and print the value of x:
Run example »
Modify Attributes
You can also modify attribute values:
Example
Set the value of x to 40:
Run example »
Example
Change the value of x to 25:
public class MyClass {
int x = 10;
Run example »
If you don't want the ability to override existing values, declare the attribute as final:
Example
public class MyClass {
final int x = 10;
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”.
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 :
As we declare variables like (type name;). This notifies the compiler that we will use name to
refer to data whose type is type. With a primitive variable, this declaration also reserves the
proper amount of memory for the variable. So for reference variable, type must be strictly a
concrete class name. In general,we can’t create objects of an abstract class or an interface.
Dog tuffy;
If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an
object is actually created and assigned to it. Simply declaring a reference variable does not
create an object.
Initializing an object
The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory. The new operator also invokes the class constructor.
filter_none
edit
play_arrow
brightness_4
// Class Declaration
// Instance Variables
String name;
String breed;
int age;
String color;
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
// method 1
return name;
}
// method 2
return breed;
// method 3
return age;
// method 4
return color; }
@Override
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
System.out.println(tuffy.toString());
Output:
Hi my name is tuffy.
My breed,age and color are papillon,5,white
• This class contains a single constructor. We can recognize a constructor because its declaration
uses the same name as the class and it has no return type. The Java compiler differentiates the
constructors based on the number and the type of the arguments. The constructor in
the Dog class takes four arguments. The following statement provides
“tuffy”,”papillon”,5,”white” as values for those arguments:
• Dog tuffy = new Dog("tuffy","papillon",5, "white");
Note : All classes have at least one constructor. If a class does not explicitly declare any, the
Java compiler automatically provides a no-argument constructor, also called the default
constructor. This default constructor calls the class parent’s no-argument constructor (as it
contain only one statement i.e super();), or the Object class constructor if the class has no
other parent (as Object class is parent of all classes either directly or indirectly).
What is an Interface?
An interface is just like Java Class, but it only has static constants and abstract
method. Java uses Interface to implement multiple inheritance. A Java class can
implement multiple Java Interfaces. All methods in an interface are implicitly
public and abstract.
interface {
//methods
}
To use an interface in your class, append the keyword "implements" after your
class name followed by the interface name.
Suppose you have a requirement where class "dog" inheriting class "animal" and
"Pet" (see image below). But you cannot extend two classes in Java. So what
would you do? The solution is Interface.
Class Dog can extend to class "Animal" and implement interface as "Pet".
interface Pet{
public void test();
}
class Dog implements Pet{
public void test(){
System.out.println("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
p.test();
}
}
Step 2) Save , Compile & Run the code. Observe the Output.
Java Fields
At its most basic, a Java field is a variable. This means it represents a value, such as text or a numeric
value. For example, the variable isbn could be declared to hold the ISBN number of a publication. Fields
are declared within classes of your code.
Note that each variable has its own type, which defines what type of data can be stored in the field. This is
a requirement. The types include String, int, double, long, boolean, and others.
Java Methods
A method is a function. That is, it is a block of code that carries out an operation. Like fields, methods
need to be inside classes. A method can accept values from other parts of the program, and they can send
results back to other parts of the program.
A method can also have a type, as a field would. If the method is not going to be sending any information
to other parts of the program, the type is set as void. However, if a method will be accepting and returning
information, you need to specify which type of information. Let's see how this works with parameters and
returning information.
If a method is set up to receive information, these values are called parameters. A parameter is a field that
is sent to and from methods. The following code creates a method that will return an integer value.
Therefore, it needs to have a type of int when the method is defined.
Initializing Fields
As you have seen, you can often provide an initial value for a field in its declaration:
// initialize to 10
public static int capacity = 10;
// initialize to false
private boolean full = false;
}
This works well when the initialization value is available and the initialization can be put on one line. However, this
form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error
handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in
constructors, where error handling or other logic can be used. To provide the same capability for class variables, the
Java programming language includes static initialization blocks.
Note: It is not necessary to declare fields at the beginning of the class definition, although this is the most common
practice. It is only necessary that they be declared and initialized before they are used.
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.
Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The
runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
There is an alternative to static blocks — you can write a private static method:
class Whatever {
public static varType myVar = initializeClassVariable();
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a
block of code between multiple constructors.
A final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance. Here
is an example of using a final method for initializing an instance variable:
class Whatever {
private varType myVar = initializeInstanceVariable();
Constructor has same name as the class and looks like this in a java code.
You may get a little lost here as I have not shown you any initialization example, lets
have a look at the code below:
BeginnersBook.com
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
constructorinto 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.
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.
Parameterized constructor
Constructor with arguments(or you can say parameters) is known as Parameterized
constructor.
int empId;
String empName;
Destructors are other concept of object oriented programming. Constructors are called when the
object is created, and the destructor is called when the object is erased. A object is by the way
like a clone of a class. That way there can be several objects or instances of a class.
In Java, programmers don’t need to worry about destructors. There is no syntax for destructors in
java. Objects are destructed but there is no destructor. The Java Virtual Machine handles that for
you. In other languages like c++ or c# you can also write a destructor but not in java. That is
probably because destructors are usually used for doing things that try-finally blocks can already
do so there is no necessity.
• In C/C++, programmer is responsible for both creation and destruction of objects. Usually
programmer neglects destruction of useless objects. Due to this negligence, at certain point, for
creation of new objects, sufficient memory may not be available and entire program will
terminate abnormally causing OutOfMemoryErrors.
• But in Java, the programmer need not to care for all those objects which are no longer in use.
Garbage collector destroys these objects.
• Garbage collector is best example of Daemon thread as it is always running in background.
• Main objective of Garbage Collector is to free heap memory by destroying unreachable
objects.
Important terms :
1. Unreachable objects : An object is said to be unreachable iff it doesn’t contain any reference
to it. Also note that objects which are part of island of isolation are also unreachable.
6. Eligibility for garbage collection : An object is said to be eligible for GC(garbage collection)
iff it is unreachable. In above image, after i = null; integer object 4 in heap area is eligible for
garbage collection.
Ways to make an object eligible for GC
• Even though programmer is not responsible to destroy useless objects but it is highly
recommended to make an object unreachable(thus eligible for GC) if it is no longer required.
• There are generally four different ways to make an object eligible for garbage collection.
1. Nullifying the reference variable
2. Re-assigning the reference variable
3. Object created inside method
4. Island of Isolation
All above ways with examples are discussed in separate article : How to make object
eligible for garbage collection
t1 = null;
System.gc();
t2 = null;
Runtime.getRuntime().gc();
}
@Override
Output:
Garbage collector called
Object garbage collected : Test@46d08f12
Garbage collector called
Object garbage collected : Test@481779b8
3. There is no guarantee that any one of above two methods will definitely run Garbage
Collector.
4. The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()
Finalization
• Just before destroying an object, Garbage Collector calls finalize() method on the object to
perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that
object.
• finalize() method is present in Object class with following prototype.
• protected void finalize() throws Throwable
Based on our requirement, we can override finalize() method for perform our cleanup
activities like closing connection from database.
Note :
1. The finalize() method called by Garbage Collector not JVM. Although Garbage Collector is one
of the module of JVM.
2. Object class finalize() method has empty implementation, thus it is recommended to
override finalize() method to dispose of system resources or to perform other cleanup.
3. The finalize() method is never invoked more than once for any given object.
4. If an uncaught exception is thrown by the finalize() method, the exception is ignored and
finalization of that object terminates.
Example:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate
// Call by Value
// Callee
class CallByValue {
x++;
y++;
// Caller
int a = 10;
int b = 20;
System.out.println("Value of a: " + a
object.Example(a, b);
System.out.println("Value of a: "
Output:
Value of a: 10 & b: 20
Value of a: 10 & b: 20
Shortcomings:
• Inefficiency in storage allocation
• For objects and arrays, the copy semantics are costly
2. Call by reference(aliasing): Changes made to formal parameter do get transmitted back to the
caller through parameter passing. Any changes to the formal parameter are reflected in the
actual parameter in the calling environment as formal parameter receives a reference (or
pointer) to the actual data. This method is also called as <em>call by reference. This method is
efficient in both time and space.
// Call by Reference
// Callee
class CallByReference {
int a, b;
CallByReference(int x, int y)
a = x;
b = y;
obj.a += 10;
obj.b += 20;
// Caller
CallByReference object
System.out.println("Value of a: "
+ object.a
+ object.b);
object.ChangeValue(object);
// Displaying values
System.out.println("Value of a: "
+ object.a
+ object.b);
Output:
Value of a: 10 & b: 20
Value of a: 20 & b: 40
1. Value type
2. Reference type
3. Pointer type
Value Type:
A data type is a value type if it holds a data value within its own memory space. It means
variables of these data types directly contain their values.
All the value types derive from System.ValueType, which in-turn, derives
from System.Object.
For example, consider integer variable int i = 100;
The system stores 100 in the memory space allocated for the variable 'i'. The following image
illustrates how 100 is stored at some hypothetical location in the memory (0x239110) for 'i':
• bool
• byte
• char
• decimal
• double
• enum
• float
• int
• long
• sbyte
• short
• struct
• uint
• ulong
• ushort
Passing by Value:
When you pass a value type variable from one method to another method, the system creates
a separate copy of a variable in another method, so that if value got changed in the one
method won't affect on the variable in another method.
Console.WriteLine(x);
}
Console.WriteLine(i);
ChangeValue(i);
Console.WriteLine(i);
}
Try it
Output:
100
200
100
In the above example, variable i in Main() method remains unchanged even after we pass it
to the ChangeValue() method and change it's value there.
Reference Type
Unlike value types, a reference type doesn't store its value directly. Instead, it stores the
address where the value is being stored. In other words, a reference type contains a pointer to
another memory location that holds the data.
The following image shows how the system allocates the memory for the above string
variable.
Memory allocation
for Reference type
As you can see in the above image, the system selects a random location in
memory (0x803200) for the variable 's'. The value of a variable s is 0x600000 which is the
memory address of the actual data value. Thus, reference type stores the address of the
location where the actual value is stored instead of value itself.
• String
• All arrays, even if their elements are value types
• Class
• Delegates
Pass by Reference
When you pass a reference type variable from one method to another, it doesn't create a new
copy; instead, it passes the address of the variable. If we now change the value of the variable
in a method, it will also be reflected in the calling method.
ChangeReferenceType(std1);
Console.WriteLine(std1.StudentName);
}
Try it
Output:
Steve
In the above example, since Student is an object, when we send the Student object std1 to the
ChangeReferenceType() method, what is actually sent is the memory address of std1. Thus,
when the ChangeReferenceType() method changes StudentName, it is actually changing
StudentName of std1, because std1 and std2 are both pointing to the same address in
memory. Therefore, the output is Steve .
Null
Reference types have null value by default, when they are not initialized. For example, a
string variable (or any other variable of reference type datatype) without a value assigned to
it. In this case, it has a null value, meaning it doesn't point to any other memory location,
because it has no value yet.
Null Reference
type
A value type variable cannot be null because it holds a value not a memory address.
However, value type variables must be assigned some value before use. The compiler will
give an error if you try to use a local value type variable without assigning a value to it.
Console.WriteLine(i);
}
C# 2.0 introduced nullable types for value types so that you can assign null
to a value type variable or declare a value type variable without assigning a value to it.
However, value type field in a class can be declared without initialization (field not a local
variable in the function) . It will have a default value if not assigned any value, e.g., int will
have 0, boolean will have false and so on.
Console.WriteLine(mcls.i);
Output:
Points to Remember :
1. Value type stores the value in its memory space, whereas reference type stores the address of the
value where it is stored.
2. Primitive data types and struct are of the 'Value' type. Class objects, string, array, delegates are
reference types.
3. Value type passes byval by default. Reference type passes byref by default.
4. Value types and reference types stored in Stack and Heap in the memory depends on the scope of the
variable.
Overloading in Java
Overloading allows different methods to have the same name, but different signatures where
the signature can differ by the number of input parameters or type of input parameters or
both. Overloading is related to compile time (or static) polymorphism.
1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
Intro to Loops
In programming languages, looping is a feature which facilitates the execution of a set
of instructions until the controlling Boolean-expression evaluates to false.
Java provides different types of loops to fit any programming need. Each loop has
its own purpose and a suitable use case to serve.
if Statement
The syntax of if-then statement in Java is:
if (expression) {
// statements
Therefore, we can say that: For each element in items, assign the element to
the item variable and run the body of the loop.
Let’s have a look at the simple example:
1 int[] intArr = { 0,1,2,3,4 };
2 for (int num : intArr) {
3 System.out.println("Enhanced for-each loop: i = " + num);
4 }
We can use it to iterate over various Java’s data structures:
Given a List<String> list object – we can iterate it:
1 for (String item : list) {
2 System.out.println(item);
3 }
We can similarly iterate over a Set<String> set:
1 for (String item : set) {
2 System.out.println(item);
3 }
And, given a Map<String,Integer> map we can iterate over it as well:
1 for (Entry<String, Integer> entry : map.entrySet()) {
2 System.out.println(
3 "Key: " + entry.getKey() +
4 "-" +
5 "Value: " + entry.getValue());
}
6
Iterable.forEach()
Since Java 8, we can leverage for-each loops in a slightly different way. We now
have a dedicated forEach() method in the Iterable interface that accepts a lambda
expression representing an action we want to perform.
Internally, it simply delegates the job to the standard loop:
1 default void forEach(Consumer<? super T> action) {
2 Objects.requireNonNull(action);
3 for (T t : this) {
4 action.accept(t);
5 }
}
6
Let’s have a look at the example:
1
List<String> names = new ArrayList<>();
2 names.add("Larry");
3 names.add("Steve");
4 names.add("James");
5 names.add("Conan");
names.add("Ellen");
6
7
names.forEach(name -> System.out.println(name));
8
While Loop
The while loop is Java’s most fundamental loop statement. It repeats a statement or
a block of statements while its controlling Boolean-expression is true.
The syntax of the while loop is:
1 while (Boolean-expression)
2 statement;
The loop’s Boolean-expression is evaluated before the first iteration of the loop –
which means that if the condition is evaluated to false, the loop might not run even
once.
Switch Statement
The switch statement is a multi-way branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression. Basically, the
expression can be byte, short, char, and int primitive data types. Beginning with JDK7, it also
works with enumerated types ( Enums in java), the String class and Wrapper classes.
Syntax of Switch-case :
// switch statement
switch(expression)
{
// case statements
// values must be of same type of expression
case value1 :
// Statements
break; // break is optional
case value2 :
// Statements
break; // break is optional
Java Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used
to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.This example jumps out of the loop
when i is equal to 4:
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
Break Example
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
if (i == 4) {
break;
}
}
Continue Example
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
System.out.println(i);
i++;
}
If a loop exists inside the body of another loop, it's called nested loop. Here's an example of
nested for loop.
Here, the outer loop iterates 5 times. In each iteration of outer loop, the inner loop iterates 2
times.