Você está na página 1de 62

What is Java?

JAVA is an object-oriented, cross platform, multi-purpose programming language produced by Sun


Microsystems. First released in 1995, it was developed to be a machine independent web technology. It
was based on C and C++ syntax to make it easy for programmers from those communities to learn. Since
then, it has earned a prominent place in the world of computer programming.

Java has many characteristics that have contributed to its popularity:

• 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

The Java Platform


One thing that distinguished Java from some other languages is its ability to run the same compiled code
across multiple operating systems.
In other languages, the source code (code that is written by the programmer), is compiled by a compiler
into an executable file. This file is in machine language, and is intended for a single operating
system/processor combination, so the programmer would have to re-compile the program separately for
each new operating system/processor combination.
Java is different in that it does not compile the code directly into machine language code. Compilation
creates bytecode out of the source code. Bytecode generally looks something like this:

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.

Downloading and Installing


To download the JDK, goto http://www.oracle.com/technetwork/java/javase/downloads/index.html.
Click on "JDK with NetBeans Bundle". Follow the instructions for downloading the JDK installation file.
Windows: If you are running Windows, simply run the executable file and follow the installation
instructions.
Unix, Solaris, or Linux: For Linux and Unix, download the "jdk1 6.0" for Linux systems. Save the
downloaded file in any drive. Once you have saved the file, extract it to a place that you can remember, by
using Terminal or by double clicking on the file. When you have finished extracting the file, copy the JDK
1.6.0 folder and paste it in the usr/local(To paste to the usr/local directory, you have to be in root) so that
every user can use the java files. You can delete the downloaded zip file so that it doesn't take up space on
your drive.
Macintosh: The latest available JDK is automatically installed by the operating system. Because Java for
Macintosh is developed and maintained by Apple, in coordination with Sun, the current version on the
Macintosh may not be the current version that is available from Sun.

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.

For Windows Users

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

public class HelloWorld


{
public static void main (String[] args)
{
System.out.println("Hello World!");
}
}

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.

System.out.println("Hello World!");//This is an inline comment


/*
*This is a block comment
*/
System.out.println("Hello World!");
/**
*This is a Javadoc comment
*/
public static void main (String[] args)
{
System.out.println("Hello World!");
}

What is Java Platform?


Java platform is a collection of programs that help to develop and run programs
written in the Java programming language. Java platform includes an execution
engine, a compiler, and a set of libraries. JAVA is platform-independent language.
It is not specific to any processor or operating system.

Java program structure


Let’s use the example of HelloWorld Java program to understand structure and
features of the class. This program is written on few lines, and its only task is to print
“Hello World from Java” on the screen. Refer the following picture.
1.“package sct”:

It is package declaration statement. The package statement defines a namespace in


which classes are stored. The package is used to organize the classes based on
functionality. If you omit the package statement, the class names are put into the
default package, which has no name. Package statement cannot appear anywhere in
the program. It must be the first line of your program or you can omit it.

2.“public class HelloWorld”:

This line has various aspects of java programming.

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:

We can write comments in java in two ways.

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.

4. “public static void main (String [ ] args)”:


Its method (Function) named main with string array as an argument.

a. public: Access Modifier

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.

d. Method content inside curly braces. { }

5. System.out.println("Hello World from Java") :

a. System: It is the name of Java utility class.

b. out:It is an object which belongs to System class.

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 Basic Input and Output

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.

Let's take an example to output a line.

1. class AssignmentOperator {
2. public static void main(String[] args) {
3.
4. System.out.println("Java programming is interesting.");
5. }
6. }

When you run the program, the output will be:

Java programming is interesting.

Here, println is a method that displays the string inside quotes.

What's the difference between println(), print() and printf()?


• print() - prints string inside the quotes.
• println() - prints string inside the quotes similar like print() method. Then the cursor moves to the
beginning of the next line.
• printf() - it provides string formatting (similar to printf in C/C++ programming).

Example 2: print() and println()


1. class Output {
2. public static void main(String[] args) {
3.
4. System.out.println("1. println ");
5. System.out.println("2. println ");
6.
7. System.out.print("1. print ");
8. System.out.print("2. print");
9. }
10. }

When you run the program, the output will be:

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;

Learn more about Java import

Then, we will create an object of Scanner class which will be used to get input from the user.

Scanner input = new Scanner(System.in);

int number = input.nextInt();

Example 5: Get Integer Input From the User


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. System.out.print("Enter an integer: ");
9. int number = input.nextInt();
10. System.out.println("You entered " + number);
11. }
12. }

When you run the program, the output will be:

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

When you run the program, the output will be:

Enter float: 2.343


Float entered = 2.343
Enter double: -23.4
Double entered = -23.4
Enter text: Hey!
Text entered = Hey!.

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

modifier static final dataType variableName = value; //constant within a class


Notes

It is convention to capitalize the variable name of a constant.

Declaring a field as 'final' ensures that it is constant and cannot change.

The modifier specifies the scope of the 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

//constants within a class


public class Human {
public static final int NUMBER_OF_EARS = 2;
}

//accessing a class constant


int ears = Human.NUMBER_OF_EARS;

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.

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. {
6. int n=90;//local variable
7. }
8. }//end of class

Mixed Mode Operation in java

The MODULUS Operator %


The modulus operator finds the modulus of its first operand with respect to
the second. That is, it produces the remainder of dividing the first value by
the second value. For example:

22 % 6 = 4 because 22 / 6 = 3 with a remainder of 4

Confusing DIVISIONS
Be careful when performing integer division. When dividing an integer
by an integer, the answer will be an integer (not rounded).

Compare these divisions: (5 is an integer while 5.0 is a double)

Integer division 8/5=1


Double division 8.0 / 5.0 = 1.6
Mixed division 8.0 / 5 = 1.6

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.

Mixed Mode Operations


Consider these examples:

int a; int a, b; c = ( double) b/a;


double b, c; double c; c= 21.0 / 5
a = 3; b = 21; c = 4.2
b = 5.1; a = 5;
c= a + b; c = b/a; It is possible to force the type
you want by type casting.
When adding an int to Integer division takes Be careful to force
adouble, the int is place and gives an answer the double to either the
converted to a double for of 4. This answer is stored numerator or denominator,
the purpose of as a double 4.0. not both.
adding. The memory
space retains the int. The But what if we wanted the c = ( double) (b/a);
location of the sum, c, correct division answer ... gives an answer 4.0 since
must be a double. integer division is done first.

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 VS REFERENCE TYPE IN


JAVA
Variables are the place in memory to hold value. Now what sort of value a variable will hold divides them
into two major types.
1) Primitive type – They store the value of variable.
2) Reference type – They store the reference of the object. Reference means they store address of object in
computer memory.

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.

• Primitive values are compared during comparison operation.

• Returns a primitive value.


• Provided by the language itself i.e. they already exists.

• Default value is 0 or flase in caseof Boolean.

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

• Address is copied during assignment operation.

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

• Default value is null, that means “reference to nothing”.

Example:
Account a = new Account();

OOPS Concepts in Java with Examples

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.

Object Oriented Programming popularly known as OOP, is used in a modern


programming language like Java
Core OOPS concepts are
1) Class
The class is a group of similar entities. It is only an logical component and not the
physical entity. For example, if you had a class called “Expensive Cars” it could
have objects like Mercedes, BMW, Toyota, etc. Its properties(data) can be price or
speed of these cars. While the methods may be performed with these cars are
driving, reverse, braking etc.

2) Object

An object can be defined as an instance of a class, and there can be multiple


instances of a class in a program. An Object contains both the data and the
function, which operates on the data. For example - chair, bike, marker, pen, table,
car, etc.

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

Polymorphism refers to the ability of a variable, object or function to take on


multiple forms. For example, in English, the verb run has a different meaning if
you use it with a laptop, a foot race, and business. Here, we understand the
meaning of run based on the other words used along with it.The same also applied
to Polymorphism.

5) Abstraction

An abstraction is an act of representing essential features without including


background details. It is a technique of creating a new data type that is suited for a
specific application. For example, while driving a car, you do not have to be
concerned with its internal working. Here you just need to concern about parts like
steering wheel, Gears, accelerator, etc.

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

Association is a relationship between two objects. It defines the diversity between


objects. In this OOP concept, all object have their separate lifecycle, and there is
no owner. For example, many students can associate with one teacher while one
student can also associate with multiple teachers.

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

A composition is a specialized form of Aggregation. It is also called "death"


relationship. Child objects do not have their lifecycle so when parent object deletes
all child object will also delete automatically. For that, let’s take an example of
House and rooms. Any house can have several rooms. One room can’t become part
of two different houses. So, if you delete the house room will also be deleted.

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.

Programming languages can be classified into 3 primary types

1. Unstructured Programming Languages: The most primitive of all


programming languages having sequentially flow of control. Code is
repeated through out the program
2. Structured Programming Languages: Has non-sequentially flow of
control. Use of functions allows for re-use of code.
3. Object Oriented Programming: Combines Data & Action Together.

What is Abstraction in OOPs? Learn with Java Example

What is Abstraction in OOP?


Abstraction is selecting data from a larger pool to show only the relevant details to
the object. It helps to reduce programming complexity and effort. In Java,
abstraction is accomplished using Abstract classes and interfaces. It is one of the
most important concepts of OOPs.

How to achieve Abstraction?


At a higher level, Abstraction is a process of hiding the implementation details and
showing only functionality to the user. It only indicates important things to the user
and hides the internal details, ie. While sending SMS, you just type the text and
send the message. Here, you do not care about the internal processing of the
message delivery. Abstraction can be achieved using Abstract Class and Abstract
Method in Java.

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.

Rules of Abstract Method

• Abstract methods do not have an implementation; it only has method


signature
• If a class is using an abstract method they must be declared abstract. The
opposite cannot be true. This means that an abstract class does not
necessarily have an abstract method.
• If a regular class extends an abstract class, then that class must implement
all the abstract methods of the abstract parent

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.

To achieve encapsulation in Java −

• Declare the variables of a class as private.

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

/* File name : EncapTest.java */

public class EncapTest {

private String name;

private String idNum;

private int age;


public int getAge() {

return age;

public String getName() {

return name;

public String getIdNum() {

return idNum;

public void setAge( int newAge) {

age = newAge;

public void setName(String newName) {

name = newName;

public void setIdNum( String newId) {

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 −

/* File name : RunEncap.java */


public class RunEncap {

public static void main(String args[]) {

EncapTest encap = new EncapTest();

encap.setName("James");

encap.setAge(20);

encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());

This will produce the following result −

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.

Difference between Abstraction and Encapsulation

Abstraction Encapsulation

Abstraction solves the issues at the Encapsulation solves it implementation


design level. level.

Abstraction is about hiding unwanted Encapsulation means hiding the code


details while showing most essential and data into a single unit.
information.

Abstraction allows focussing on what Encapsulation means hiding the internal


the information object must contain details or mechanics of how an object
does something for security reasons.
Composition In Java With Example
We have discussed the concept of inheritance which is a powerful mechanism of
reusing code, minimizing data redundancy, and improving the organization of object
oriented system. Inheritance is suitable only when classes are in a relationship in
which child class is a parent class. For example: A Car is a Vehicle, so the
class Car has all the features or properties of class Vehicle and in addition to its own
features. However, we cannot always have is a relationship between objects of
different classes. Let us say with example: A car is not a kind of engine. To represent
such a relationship, we have an alternative to inheritance known as composition. It is
applied when classes are in a relationship in which child class has a parent class.
Unlike Inheritance in which a subclass extends the functionality of a superclass, in
composition, a class reuses the functionality by creating a reference to the object of
the class it wants to reuse. For example: A car has a engine, a window has a button, a
zoo has a tiger.
Composition is a special case of aggregation. In other words, a restricted aggregation
is called composition. When an object contains the other object and the contained
object cannot exist without the other object, then it is called composition.

Program Example of Composition:


Let us consider the following program that demonstrates the concept of composition.
Step 1: First we create a class Bike in which we declare and define data members and
methods:

class Bike
{

// declaring data members and methods

private String color;

private int wheels;

public void bikeFeatures()

System.out.println("Bike Color= "+color + " wheels= " + wheels);


}

public void setColor(String color)

this.color = color;

public void setwheels(int wheels)

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:

class Honda extends Bike

//inherits all properties of bike class

public void setStart()

HondaEngine e = new HondaEngine();

e.start();
}

Step 3: Third we create a class HondaEngine through which we uses this class object
in above class Honda:

class HondaEngine

public void start()

System.out.println("Engine has been started.");

public void stop()

System.out.println("Engine has been stopped.");

Step 4: Fourth we create a class CompositionDemo in which we make an object


of Honda class and initialized it:

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

{
Honda h = new Honda();
h.setColor("Black");
h.setwheels(2);
h.bikeFeatures();
h.setStart();
}

Output:

Bike color= Black wheels= 2


Engine has been started

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.

Java Class Attributes


In the previous chapter, we used the term "variable" for x in the example (as shown below). It is
actually an attribute of the class. Or you could say that class attributes are variables within a
class:

Example
Create a class called "MyClass" with two attributes: x and y:

public class MyClass {


int x = 5;
int y = 3;
}

Another term for class attributes is fields.

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:

public class MyClass {


int x = 5;

public static void main(String[] args) {


MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}

Run example »

Modify Attributes
You can also modify attribute values:

Example
Set the value of x to 40:

public class MyClass {


int x;

public static void main(String[] args) {


MyClass myObj = new MyClass();
myObj.x = 40;
System.out.println(myObj.x);
}
}

Run example »

Or override existing values:

Example
Change the value of x to 25:
public class MyClass {
int x = 10;

public static void main(String[] args) {


MyClass myObj = new MyClass();
myObj.x = 25; // x is now 25
System.out.println(myObj.x);
}
}

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;

public static void main(String[] args) {


MyClass myObj = new MyClass();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}

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 or prototype 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, in order:
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, { }.
Constructors are used for initializing new objects. Fields are variables that provides the state
of the class and its objects, and methods are used to implement the behavior of the class and
its objects.
There are various types of classes that are used in real time applications such as nested
classes, anonymous classes, lambda expressions.

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 :

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

public class Dog

// Instance Variables

String name;

String breed;

int age;

String color;

// Constructor Declaration of Class

public Dog(String name, String breed,

int age, String color)

this.name = name;

this.breed = breed;

this.age = age;

this.color = color;

// method 1

public String getName()

return name;
}

// method 2

public String getBreed()

return breed;

// method 3

public int getAge()

return age;

// method 4

public String getColor()

return color; }

@Override

public String toString()

return("Hi my name is "+ this.getName()+

".\nMy breed,age and color are " +

this.getBreed()+"," + this.getAge()+

","+ this.getColor());

public static void main(String[] args)


{

Dog tuffy = new Dog("tuffy","papillon", 5, "white");

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

Ways to create object of a class


There are four ways to create objects in java.Strictly speaking there is only one way(by
using new keyword),and the rest internally use new keyword.
• Using new keyword : It is the most common and general way to create object in java. Example:

• // creating object of class Test


• Test t = new Test();
• Using Class.forName(String className) method : There is a pre-defined class in java.lang
package with name Class. The forName(String className) method returns the Class object
associated with the class with the given string name.We have to give the fully qualified name
for a class. On calling new Instance() method on this Class object returns new instance of the
class with the given string name.
• // creating object of public class Test
• // consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();
• Using clone() method: clone() method is present in Object class. It creates and returns a copy
of the object.

• // creating object of class Test
• Test t1 = new Test();

• // creating clone of above object


• Test t2 = (Test)t1.clone();

• Deserialization : De-serialization is technique of reading an object from the saved state in a


file. Refer Serialization/De-Serialization in java

• FileInputStream file = new FileInputStream(filename);


• ObjectInputStream in = new ObjectInputStream(file);
• Object obj = in.readObject();
Creating multiple objects by one type only (A good practice)
• In real-time, we need different objects of a class in different methods. Creating a number of
references for storing them is not a good practice and therefore we declare a static reference
variable and use it whenever required. In this case,wastage of memory is less. The objects that
are not referenced anymore will be destroyed by Garbage Collector of java. Example:

• Test test = new Test();


• test = new Test();
• In inheritance system, we use parent class reference variable to store a sub-class object. In this
case, we can switch into different subclass objects using same referenced variable. Example:
• class Animal {}

• class Dog extends Animal {}


• class Cat extends Animal {}

• public class Test


• {
• // using Dog object
• Animal obj = new Dog();

• // using Cat object


• obj = new Cat();
• }
What is Interface in Java with Example

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.

Syntax for Declaring Interface

interface {
//methods
}

To use an interface in your class, append the keyword "implements" after your
class name followed by the interface name.

Example for Implementing Interface

class Dog implements Pet


interface RidableAnimal extends Animal, Vehicle

Why is an Interface required?


To understand the concept of Java Interface better, let see an example. The class
"Media Player" has two subclasses: CD player and DVD player. Each having its
unique implementation method to play music.
Another class "Combo drive" is inheriting both CD and DVD (see image below).
Which play method should it inherit? This may cause serious design issues. And
hence, Java does not allow multiple inheritance.

Now let's take another example of Dog.

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.

The rulebook for interface says,

• An interface is 100% abstract class and has only abstract methods.


• Class can implement any number of interfaces.

Class Dog can extend to class "Animal" and implement interface as "Pet".

Java Interface Example:


Step 1) Copy following code into an editor.

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.

When to use Interface and Abstract Class?


• Use an abstract class when a template needs to be defined for a group of
subclasses
• Use an interface when a role needs to be defined for other classes, regardless
of the inheritance tree of these classes

Fields and Methods


Java fields and methods are core components of the programming language. Each plays a major role in
Java classes. Before we compare the two, let's briefly go over some of the key features of fields and
methods.

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.

1. public class Book {


2. String isbn;
3. String title;
4. int pageCount;
5. double price;
6. }

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.

1. // Below is a method within Book


2. public void printNotice() {
3. System.out.println("I'm a Book!");
4. }

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.

1. public int setCount(int c, String isbn) {


2. int count = c + 15;
3. String myIsbn = isbn;
4. return c;
5. }
Now that we have an understanding of fields and methods, let's compare these two Java concepts.

Fields vs. Methods


Fields and methods are alike in that they exist within classes and have a defined type. If a method returns
no values, its type is set to void. The most important distinction between the two is that Java fields can
hold information, while Java methods perform a task. On its own, a field only describes what type of
information is stored in it.
Methods and fields can also be declared with other modifiers. The type is always required when declaring
a field (or void if a method does not return a value). You may have noticed the word public in the method
declaration code. This keyword tells Java that the method can be accessed from anywhere in the program.
When declaring fields, you can also add the modifier which restricts (or opens up) access to the field. Take
a look at the code below, which uses comments to explain each of the modifier types for fields:

1. public class FieldExamples {


2. /* private means that only code in
3. this class can access the field */
4. private int locationID;
5. /* protected: only child classes (sub-classes)
6. of this class can access this field */
7. protected double price;
8. /* public: all classes can access */
9. public String author;
10. /* static: variable exists in the class, which
11. means any instance of that variable exists
12. in every instance of the class */
13. static String publicationType;
14. /* final: the value CANNOT change. This is
15. used for constant values, because the value can never change.
16. Often used in combo with static. Constants are often all-caps */
17. static final String PUB_TYPE = "Book";
18. }

Initializing Fields
As you have seen, you can often provide an initial value for a field in its declaration:

public class BedAndBreakfast {

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

Static Initialization Blocks

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();

private static varType initializeClassVariable() {

// initialization code goes here


}
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

Initializing Instance Members


Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a
constructor to initialize instance variables: initializer blocks and final methods.

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();

protected final varType initializeInstanceVariable() {

// initialization code goes here


}
}
This is especially useful if subclasses might want to reuse the initialization method. The method is final because
calling non-final methods during instance initialization can cause problems.
Constructors in Java
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.com 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. We
will cover this keyword in detail in the next tutorial.

public class Hello {


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

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.

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

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.

Garbage Collection in Java


Introduction

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

2. Integer i = new Integer(4);


3. // the new Integer object is reachable via the reference in 'i'
4. i = null;
5. // the Integer object is no longer reachable.

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

Ways for requesting JVM to run Garbage Collector


• Once we made object eligible for garbage collection, it may not destroy immediately by garbage
collector. Whenever JVM runs Garbage Collector program, then only object will be destroyed.
But when JVM runs Garbage Collector, we can not expect.
• We can also request JVM to run Garbage Collector. There are two ways to do it :
1. Using System.gc() method : System class contain static method gc() for requesting JVM
to run Garbage Collector.
2. Using Runtime.getRuntime().gc() method : Runtime class allows the application to
interface with the JVM in which the application is running. Hence by using its gc()
method, we can request JVM to run Garbage Collector.

// Java program to demonstrate requesting

// JVM to run Garbage Collector

public class Test

public static void main(String[] args) throws InterruptedException

Test t1 = new Test();

Test t2 = new Test();

// Nullifying the reference variable

t1 = null;

// requesting JVM for running Garbage Collector

System.gc();

// Nullifying the reference variable

t2 = null;

// requesting JVM for running Garbage Collector

Runtime.getRuntime().gc();
}

@Override

// finalize method is called on object once

// before garbage collecting it

protected void finalize() throws Throwable

System.out.println("Garbage collector called");

System.out.println("Object garbage collected : " + this);

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.

Parameter Passing Techniques in Java with


Examples
There are different ways in which parameter data can be passed into and out of methods and
functions. Let us assume that a function B() is called from another function A(). In this
case A is called the “caller function” and B is called the “called function or callee
function”. Also, the arguments which A sends to B are called actual arguments and the
parameters of B are called formal arguments.
Types of parameters:
• Formal Parameter : A variable and its type as they appear in the prototype of the function or
method.
Syntax:
function_name(datatype variable_name)
• Actual Parameter : The variable or expression corresponding to a formal parameter that
appears in the function or method call in the calling environment.
Syntax:
func_name(variable name(s));
Important methods of Parameter Passing
1. Pass By Value: Changes made to formal parameter do not get transmitted back to the caller.
Any modifications to the formal parameter variable inside the called function or method affect
only the separate storage location and will not be reflected in the actual parameter in the calling
environment. This method is also called as call by value.
Java in fact is strictly call by value.

Example:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate

// Call by Value

// Callee

class CallByValue {

// Function to change the value


// of the parameters

public static void Example(int x, int y)

x++;

y++;

// Caller

public class Main {

public static void main(String[] args)

int a = 10;

int b = 20;

// Instance of class is created

CallByValue object = new CallByValue();

System.out.println("Value of a: " + a

+ " & b: " + b);

// Passing variables in the class function

object.Example(a, b);

// Displaying values after

// calling the function

System.out.println("Value of a: "

+ a + " & b: " + b);


}

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.

// Java program to illustrate

// Call by Reference

// Callee

class CallByReference {

int a, b;

// Function to assign the value

// to the class variables

CallByReference(int x, int y)

a = x;

b = y;

// Changing the values of class variables


void ChangeValue(CallByReference obj)

obj.a += 10;

obj.b += 20;

// Caller

public class Main {

public static void main(String[] args)

// Instance of class is created

// and value is assigned using constructor

CallByReference object

= new CallByReference(10, 20);

System.out.println("Value of a: "

+ object.a

+ " & b: "

+ object.b);

// Changing values in class function

object.ChangeValue(object);

// Displaying values

// after calling the function

System.out.println("Value of a: "
+ object.a

+ " & b: "

+ object.b);

Output:

Value of a: 10 & b: 20
Value of a: 20 & b: 40

Value Type and Reference Type


We have learned about the data types in the previous section. In C#, these data types are
categorized based on how they store their value in the memory. C# includes following
categories of data types:

1. Value type
2. Reference type
3. Pointer type

Here, we will learn about value types and reference types.

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':

Memory allocation for Value Type


The following data types are all of value type:

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

Example: Value Type


static void ChangeValue(int x)
{
x = 200;

Console.WriteLine(x);
}

static void Main(string[] args)


{
int i = 100;

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.

For example, consider following string variable:

string s = "Hello World!!";

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.

The following data types are of reference type:

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

Example: Reference Type Variable


static void ChangeReferenceType(Student std2)
{
std2.StudentName = "Steve";
}

static void Main(string[] args)


{
Student std1 = new Student();
std1.StudentName = "Bill";

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.

Example: Compile Time Error


void someFunction()
{
int i;

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.

Example: Value Type Field


class myClass
{
public int i;
}

myClass mcls = new myClass();

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

Here expression is a boolean expression (returns either true or false).


If the expression is evaluated to true, statement(s) inside the body of if (statements inside
parenthesis) are executed.
If the expression is evaluated to false, statement(s) inside the body of if are skipped from
execution.

Simple for Loop


A for loop is a control structure that allows us to repeat certain operations by
incrementing and evaluating a loop counter.
Before the first iteration, the loop counter gets initialized, then the condition
evaluation is performed followed by the step definition (usually a simple
incrementation).
The syntax of the for loop is:
1 for (initialization; Boolean-expression; step)
2 statement;
Let’s see it in a simple example:
1 for (int i = 0; i < 5; i++) {
2 System.out.println("Simple for loop: i = " + i);
3 }
The initialization, Boolean-expression, and step used in for statement are optional.
Here’s an example of an infinite for loop:
1 for ( ; ; ) {
2 // Infinite for loop
3 }

Labeled for Loops


We can also have labeled for loops. It’s useful if we’ve got nested for loops so that
we can break/continue from aspecific for loop:
aa: for (int i = 1; i <= 3; i++) {
1 if (i == 1)
2 continue;
3 bb: for (int j = 1; j <= 3; j++) {
4 if (i == 2 && j == 2) {
break aa;
5
}
6 System.out.println(i + " " + j);
7 }
}
8
9
10

Enhanced for Loop


Since Java 5, we have a second kind of for loop called the enhanced
for which makes it easier to iterate over all elements in an array or a collection.
The syntax of the enhanced for loop is:
1 for(Type item : items)
2 statement;
Since this loop is simplified in comparison to the standard for loop, we need to
declare only two things when initializing a loop:

1. The handle for an element we’re currently iterating over


2. The source array/collection we’re iterating

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.

Let’s have a look at a simple example:


1 int i = 0;
2 while (i < 5) {
3 System.out.println("While loop: i = " + i);
4 }
Do-While Loop
The do-while loop works just like the while loop except for the fact that the first
condition evaluation happens after the first iteration of the loop:
1 do {
2 statement;
3 } while (Boolean-expression);
Let’s have a look at a simple example:
1 int i = 0;
2 do {
3 System.out.println("Do-While loop: i = " + i++);
4 } while (i < 5);

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

// We can have any number of case statements


// below is default statement, used when none of the cases is true.
// No break is needed in the default case.
default :
// Statements
}

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.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}

Break and Continue in While Loop


You can also use break and continue in while loops:

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++;
}

Nested Loop in Java

If a loop exists inside the body of another loop, it's called nested loop. Here's an example of
nested for loop.

1. for (int i = 1; i <= 5; ++i) {


2.
3. // codes inside the body of outer loop
4.
5. for (int j = 1; j <=2; ++j) {
6. // codes inside the body of both outer and inner loop
7. }
8.
9. // codes inside the body of outer loop
10. }
Here, a for loop is inside the body another for loop.
It should be noted that, you can put one type of loop inside the body of another type. For
example, you can put a while loop inside the body of a for loop.
Example 1: Java Nested for Loop
1. class NestedForLoop {
2. public static void main(String[] args) {
3.
4. for (int i = 1; i <= 5; ++i) {
5.
6. System.out.println("Outer loop iteration " + i);
7.
8. for (int j = 1; j <=2; ++j) {
9. System.out.println("i = " + i + "; j = " + j);
10. }
11. }
12. }
13. }

When you run the program, the output will be:

Outer loop iteration 1


i = 1; j = 1
i = 1; j = 2
Outer loop iteration 2
i = 2; j = 1
i = 2; j = 2
Outer loop iteration 3
i = 3; j = 1
i = 3; j = 2
Outer loop iteration 4
i = 4; j = 1
i = 4; j = 2
Outer loop iteration 5
i = 5; j = 1
i = 5; j = 2

Here, the outer loop iterates 5 times. In each iteration of outer loop, the inner loop iterates 2
times.

Let's take another example.

Example 2: Java Nested Loop


1. class NestedLoop {
2. public static void main(String[] args) {
3.
4. int i = 1;
5.
6. while (i <= 5) {
7.
8. System.out.println("Outer loop iteration " + i);
9.
10. for (int j = 1; j <= 2; ++j) {
11. System.out.println("i = " + i + "; j = " + j);
12. }
13.
14. ++i;
15. }
16. }
17. }

The output of this program and above program is same.

Você também pode gostar