4. 1 Java Unit 1 Notes
4. 1 Java Unit 1 Notes
UNIT-1
INTRODUCTION TO JAVA
HISTORY
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team. Initially it
was designed for small, embedded systems in electronic appliances like set-top
[Link], it was called "Greentalk" by James Gosling, and the file extension was
.gt. After that, it was called Oak and was developed as a part of the Green [Link]
1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies. In 1995, Time magazine called Java one of the Ten Best Products of
1995.
JDK 1.0 was released on January 23, 1996. After the first release of Java, there have
been many additional features added to the language. Now Java is being used in
Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.
Divided Into In POP, program is divided into small In OOP, program is divided into parts
parts called functions. called objects.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access POP does not have any access OOP has access specifiers named
Specifiers specifier. Public, Private, Protected, etc.
Data Moving In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other
through member functions.
Expansion To add new data and function in POP OOP provides an easy way to add new
is not so easy. data and function.
Data Access In POP, Most function uses Global In OOP, data can not move easily from
data for sharing that can be accessed function to function,it can be kept
freely from function to function in public or private so we can control
the system. the access of data.
Data Hiding POP does not have any proper way OOP provides Data Hiding so
for hiding data so it is less secure. provides more security.
Examples Example of POP are : C, VB, Example of OOP are : C++, JAVA,
FORTRAN, Pascal. [Link], C#.NET.
Applications of OOPs:
Real-Time System design: Real-time system inherits complexities and makes it
difficult to build them. OOP techniques make it easier to handle those complexities.
Hypertext and Hypermedia: Hypertext is similar to regular text as it can be stored,
searched, and edited easily. Hypermedia on the other hand is a superset of hypertext.
OOP also helps in laying the framework for hypertext and hypermedia.
AI Expert System: These are computer application that is developed to solve complex
problems which are far beyond the human brain. OOP helps to develop such an AI
expert System
Office automation System: These include formal as well as informal electronic
systems that primarily concerned with information sharing and communication to
and from people inside and outside the organization. OOP also help in making office
automation principle.
Neural networking and parallel programming: It addresses the problem of
prediction and approximation of complex-time varying systems. OOP simplifies the
entire process by simplifying the approximation and prediction ability of the network.
Stimulation and modeling system: It is difficult to model complex systems due to
varying specifications of variables. Stimulating complex systems require modeling and
understanding interaction explicitly. OOP provides an appropriate approach for
simplifying these complex models.
Object-oriented database: The databases try to maintain a direct correspondence
between the real world and database object in order to let the object retain it identity
and integrity.
Client-server system: Object-oriented client-server system provides the IT
infrastructure creating object-oriented server internet(OCSI) applications.
CIM/CAD/CAM systems: OOP can also be used in manufacturing and designing
applications as it allows people to reduce the efforts involved. For instance, it can be
used while designing blueprints and flowcharts. So it makes it possible to produce
these flowcharts and blueprint accurately.
JAVA FEATURES
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According
to Sun Microsystem, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
Platform Independent
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by
an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both
32 and 64-bit architectures in Java
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++. Java
supports dynamic compilation and automatic memory management (garbage collection).
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of
JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
PROGRAM STRUCTURE
Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of
the program
Package Declaration
The package declaration is optional. It is placed just after the documentation section. In this
section, we declare the package name in which the class is placed. Note that there can
be only one package statement in a Java program. It must be defined before any class and
interface declaration.
Import Statements
We use the import keyword to import the class. It is written before the class declaration
and after the package statement. We use the import statement in two ways, either import a
specific class or import all classes of a particular package. In a Java program, we can use
multiple import statements.
Interface Section
Class Definition
It is vital part of a Java program. The class is a blueprint of a Java program. It contains
information about user-defined methods, variables, and constants. Every Java program has
at least one class that contains the main() method.
Step 1:Write a program on the notepad and save it with .java (for example, [Link])
extension.
1. class DemoFile
2. {
3. public static void main(String args[])
4. {
5. [Link]("Hello!");
6. [Link]("Java");
7. }
8. }
Step 2:Open Command Prompt.
Step 3:
9. Set the directory in which the .java file is saved. In our case, the .java file is saved in
C:\\demo.
10.
Step 4:
Use the following command to compile the Java program. It generates a .class file in the
same folder. It also shows an error if any
1. javac [Link]
Step 5:
Use the following command to run the Java program:
1. java DemoFile
Java Tokens
The Java compiler breaks the line of code into text (words) is called Java tokens. These are
the smallest element of the Java program. The Java compiler identified these words as
tokens. These tokens are separated by the delimiters. It is useful for compilers to detect
errors. Remember that the delimiters are not part of the Java tokens.
1. token <= identifier | keyword | separator | operator | literal | comment
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
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.
Types of Variables
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 an
instance variable. It is not declared as static
.
It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
o Multidimensional Array
Multidimensional Arrays can be defined in simple words as array of arrays. Data in
multidimensional arrays are stored in tabular form (in row major order).
Syntax:
data_type[1st dimension][2nd dimension][]..[Nth
dimension] array_name = new data_type[size1][size2]….[sizeN];
where:
data_type: Type of data to be stored in the array. For example: int, char, etc.
dimension: The dimension of the array created.
For example: 1D, 2D, etc.
array_name: Name of the array
size1, size2, …, sizeN: Sizes of the dimensions respectively.
Examples:
Two dimensional array:
int[][] twoD_arr = new int[10][20];
Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These
are the most basic data types available in Java language.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Arithmetic Operators
Unary Operators
Assignment Operator
Relational Operators
Logical Operators
Ternary Operator
Bitwise Operators
Shift Operators
instance of operator
Arithmetic Operators: They are used to perform simple arithmetic operations on
primitive data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
Unary Operators: Unary operators need only one operand. They are used to
increment, decrement or negate a value.
– :Unary minus, used for negating the values.
+ :Unary plus, indicates positive value (numbers are positive without this,
however). It performs an automatic conversion to int when the type of its
operand is byte, char, or short. This is called unary numeric promotion.
++ :Increment operator, used for incrementing the value by 1. There are
two varieties of increment operator.
Post-Increment: Value is first used for computing the result and
then incremented.
Pre-Increment: Value is incremented first and then result is
computed.
-- : Decrement operator, used for decrementing the value by 1. There are
two varieties of decrement operator.
Post-decrement : Value is first used for computing the result
and then decremented.
Pre-Decrement : Value is decremented first and then result is
computed.
Assignment Operator : ‘=’ Assignment operator is used to assign a value to any
variable. It has a right to left associativity, i.e value given on right hand side of
operator is assigned to the variable on the left and therefore right hand side value
must be declared before using it or should be a constant.
General format of assignment operator is, variable = value;.
Relational Operators : These operators are used to check for relations like equality,
greater than, less than. They return boolean result after the comparison and are
extensively used in looping statements as well as conditional if else statements.
General format is,
variable relation_operator value
Some of the relational operators are-
==, Equal to : returns true if left hand side is equal to right hand side.
!=, Not Equal to : returns true if left hand side is not equal to right hand
side.
<, less than : returns true if left hand side is less than right hand side.
<=, less than or equal to : returns true if left hand side is less than or equal
to right hand side.
>, Greater than : returns true if left hand side is greater than right hand
side.
>=, Greater than or equal to: returns true if left hand side is greater than
or equal to right hand side.
Logical Operators : These operators are used to perform “logical AND” and “logical
OR” operation, i.e. the function similar to AND gate and OR gate in digital electronics.
One thing to keep in mind is the second condition is not evaluated if the first one is
false, i.e. it has a short-circuiting effect. Used extensively to test for several conditions
for making a decision.
Conditional operators are-
&&, Logical AND : returns true when both conditions are true.
||, Logical OR : returns true if at least one condition is true.
! : Logical not operator, used for inverting a boolean value
Ternary operator : Ternary operator is a shorthand version of if-else statement. It
has three operands and hence the name ternary. General format is- condition ? if
true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the ‘?’ else execute the statements after the ‘:’.
Bitwise Operators : These operators are used to perform manipulation of individual
bits of a number. They can be used with any of the integer types. They are used when
performing update and query operations of Binary indexed tree.
&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit by bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns
the one’s complement representation of the input value, i.e. with all bits
inversed.
Shift Operators : These operators are used to shift the bits of a number left or right
thereby multiplying or dividing the number by two respectively. They can be used
when we have to multiply or divide a number by two. General format- number
shift_op number_of_places_to_shift;
<<, Left shift operator: shifts the bits of the number to the left and fills 0
on voids left as a result. Similar effect as of multiplying the number with
some power of two.
>>, Signed Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit depends on the sign of
initial number. Similar effect as of dividing the number with some power of
two.
>>>, Unsigned Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit is set to 0.
instance of operator : Instance of operator is used for type checking. It can be used
to test if an object is an instance of a class, a subclass or an interface. General format-
object instance of class/subclass/interface
Expressions
Expressions perform the work of a Java program. Among other things, expressions are used
to compute and assign values to variables and to help control the execution flow of a
program. The job of an expression is two-fold: perform the computation indicated by the
elements of the expression and return some value.
Precedence and Associativity of Operators
Precedence and associative rules are used when dealing with hybrid equations involving
more than one type of operator. In such cases, these rules determine which part of the
equation to consider first as there can be many different valuations for the same
equation. The below table depicts the precedence of operators in decreasing order as
magnitude with the top representing the highest precedence and bottom shows the
lowest precedence.
Control Statements
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the
program flow depending upon the result of the condition provided. There are two types of
decision-making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given
below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
[Link]
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. [Link]("x + y is greater than 20");
7. }
8. }
9. }
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. [Link]("x + y is less than 10");
7. } else {
8. [Link]("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. [Link]("city is meerut");
6. }else if (city == "Noida") {
7. [Link]("city is noida");
8. }else if(city == "Agra") {
9. [Link]("city is agra");
10. }else {
11. [Link](city);
12. }
13. }
14. }
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another
if or else-if statement.
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. String address = "Delhi, India";
4.
5. if([Link]("India")) {
6. if([Link]("Meerut")) {
7. [Link]("Your city is Meerut");
8. }else if([Link]("Noida")) {
9. [Link]("Your city is Noida");
10. }else {
11. [Link]([Link](",")[0]);
12. }
13. }else {
14. [Link]("You are not living in India");
15. }
16. }
17. }
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on the
variable which is being switched. The switch statement is easier to use instead of if-else-if
statements. It also enhances the readability of the program.
Consider the following example to understand the flow of the switch statement.
[Link]
1. public class Student implements Cloneable {
2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. [Link]("number is 0");
7. break;
8. case 1:
9. [Link]("number is 1");
10. break;
11. default:
12. [Link](num);
13. }
14. }
15. }
Output:
2
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences
in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code. We use the for loop only
when we exactly know the number of times, we want to execute the block of code.
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }
[Link]
1. public class Calculattion {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. [Link]("The sum of first 10 natural numbers is " + sum);
9. }
10. }
Output:
The sum of first 10 natural numbers is 55
Java provides an enhanced for loop to traverse the data structures like array or collection.
In the for-each loop, we don't need to update the loop variable. The syntax to use the for-
each loop in java is given below.
1. for(data_type var : array_name/collection_name){
2. //statements
3. }
Consider the following example to understand the functioning of the for-each loop in Java.
[Link]
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. [Link]("Printing the content of the array names:\n");
6. for(String name:names) {
7. [Link](name);
8. }
9. }
10. }
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a
while loop. Unlike for loop, the initialization and increment/decrement doesn't take place
inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of
the loop. If the condition is true, then the loop body will be executed; otherwise, the
statements after the loop will be executed.
The flow chart for the while loop is given in the following image.
Consider the following example.
Calculation .java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. [Link](i);
8. i = i + 2;
9. }
10. }
11. }
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance.
The syntax of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
[Link]
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. do {
7. [Link](i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements.
In other words, jump statements transfer the execution control to the other part of the
program. There are two types of jump statements in Java, i.e., break and continue.
Java break statement
As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However,
it breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
Type Casting/type conversion
Converting one primitive datatype into another is known as type casting (type conversion)
in Java. You can cast the primitive datatypes in two ways namely, Widening and,
Narrowing.
Widening − Converting a lower datatype to a higher datatype is known as widening. In this
case the casting/conversion is done automatically therefore, it is known as implicit type
casting. In this case both datatypes should be compatible with each other.
Example
public class WideningExample {
public static void main(String args[]){
char ch = 'C';
int i = ch;
[Link](i);
}
}
Output
Integer value of the given character: 67
Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In
this case the casting/conversion is not done automatically, you need to convert explicitly
using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this
case both datatypes need not be compatible with each other.
Example
import [Link];
public class NarrowingExample {
public static void main(String args[]){
Scanner sc = new Scanner([Link]);
[Link]("Enter an integer value: ");
int i = [Link]();
char ch = (char) i;
[Link]("Character value of the given integer: "+ch);
}
}
Output
Enter an integer value:
67
Character value of the given integer: C
CLASSES AND OBJECTS
Object -- an encapsulation of data along with functions that act upon that data.
Class -- a blueprint for objects. A class is a user-defined type that describes what a certain
type of object will look like. A class description consists of a declaration and a definition.
Usually these pieces are split into separate files.
An object is a single instance of a class. You can create many objects from the same class
type.
};
Create Object
[Link]
1. public class CreateObjectExample1
2. {
3. void show()
4. {
5. [Link]("Welcome to java");
6. }
7. public static void main(String[] args)
8. {
9. //creating an object using new keyword
10. CreateObjectExample1 obj = new CreateObjectExample1();
11. //invoking method using the object
12. [Link]();
13. }
14. }
Output:
Welcome to java
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated
in the memory.
Output:
Bike is created
In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
1. //Java Program to demonstrate the use of the parameterized constructor.
2. class Student{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){[Link](id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student s1 = new Student(111,"Karan");
16. Student s2 = new Student(222,"Aryan");
17. //calling method to display the values of object
18. [Link]();
19. [Link]();
20. }
21. }
Output:
111 Karan
222 Aryan
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types.
Output:
111 Karan 0
222 Aryan 25
Method
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code.
Method Overloading in Java
Method Overloading is a feature that allows a class to have more than one method having
the same name, if their argument lists are different. It is similar to constructor
overloading in Java, that allows a class to have more than one constructor having different
argument lists.
There are two ways to overload the method in java.
class DisplayOverloading
{
public void disp(char c)
{
[Link](c);
}
public void disp(char c, int num)
{
[Link](c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
[Link]('a');
[Link]('a',10);
}
}
Output:
a
a 10
class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
[Link]('a');
[Link](5);
}
}
Output:
a
5
Java Garbage Collection
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object class
as: protected void finalize(){}
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes. public static void gc(){}
Access Control
Access control is a mechanism, an attribute of encapsulation which restricts the access of
certain members of a class to specific parts of a program. Access to members of a class can
be controlled using the access modifiers. There are four access modifiers in Java. They are:
1. public
2. protected
3. default
4. private
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Output:
111 ankit 5000.0
112 sumit 6000.0
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be
used as an [Link], it provides a convenient way to check the behavior of the program for
the different values. You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.
Example: To Learn java Command Line Arguments
Step 1) Copy the following code into an editor.
class Demo{
public static void main(String args[]){
String[] b={"apple","orange"};
[Link]("Argument one = "+b[0]);
[Link]("Argument two = "+b[1]);
}
}
Step 2) Save & Compile the code
Step 3) Run the code as java Demo apple orange.
Step 4) You must get an output as below.
Example program 2:
1. class CommandLineExample{
2. public static void main(String args[]){
3. [Link]("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac [Link]
2. run by > java CommandLineExample sana
Output: Your first argument is: sana
Nested Classes in Java
In Java, it is possible to define a class within another class, such classes are known
as nested classes. They enable you to logically group classes that are only used in one
place, thus this increases the use of encapsulation, and creates more readable and
maintainable code.
The scope of a nested class is bounded by the scope of its enclosing class. Thus in
below example, class NestedClass does not exist independently of class OuterClass.
A nested class has access to the members, including private members, of the class in
which it is nested. However, the reverse is not true i.e., the enclosing class does not
have access to the members of the nested class.
A nested class is also a member of its enclosing class.
As a member of its enclosing class, a nested class can be
declared private, public, protected, or package private(default).
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}
Nested classes are divided into two types −
Non-static nested classes − These are the non-static members of a class.
Static nested classes − These are the static members of a class.
Inner Class
We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
Additionally, it can access all the members of the outer class, including private data
members and methods.
Example
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
[Link]("This is an inner class");
}
}
A static class is a class that is created inside a class, is called a static nested class in Java. It
cannot access non-static data members and methods. It can be accessed by outer class
name.
o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members or
[Link]
1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){[Link]("data is "+data);}
5. }
6. public static void main(String args[]){
7. [Link] obj=new [Link]();
8. [Link]();
9. }
10. }
Output:
data is 30