JAVA Unit 1
JAVA Unit 1
History of Java
Java was originally designed for interactive television, but it was too advanced technology for
the digital cable television industry at the time. The history of Java starts with the Green Team.
Java team members initiated this project to develop a language for digital devices such as set-
top boxes, televisions, etc. However, it was best suited for internet programming. Later, Java
technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic".
Java was developed by James Gosling, who is known as the father of Java, in 1995. James
Gosling and his team members started the project in the early '90s.
Java is used in internet programming, mobile devices, games, e-business solutions, etc.
Following are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Why Java was named as "Oak"?
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
the U.S.A., France, Germany, Romania, etc.
T]\
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
7) Why had they chose the name Java for Java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They
wanted something that reflected the essence of the technology: revolutionary, dynamic, lively,
cool, unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was
so unique, most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a
kind of espresso bean. Java name was chosen by James Gosling while having a cup of coffee
nearby his office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) 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.
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for
creating web applications in Java.
3) Enterprise Application
An application which is created for mobile devices is called a mobile application. Currently,
Android and Java ME are used for creating mobile applications.
4) JavaFX It is used to develop rich internet applications. It uses a lightweight user interface
API.
Object-Oriented Programming
The word object-oriented is the combination of two words i.e. object and oriented.
The meaning of the object is an article or entity that exists in the real world.
The meaning of oriented is interested in a particular kind of thing or entity.
OOPs Concepts
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Object
An object is a real-world entity that has attributes, behavior, and properties. It is referred to as an
instance of the class. It contains member functions, variables that we have defined in the class. It
occupies space in the memory. Different objects have different states or attributes, and behaviors.
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing the details of each other's
data or code. The only necessary thing is the type of message accepted and the type of response
returned by the objects
Class
Abstraction
The concept allows us to hide the implementation from the user but shows only essential
information to the user. Using the concept developer can easily make changes and added over
time.
There are the following advantages of abstraction:
o It reduces complexity.
o It avoids delicacy.
o Eases the burden of maintenance
o Increase security and confidentially.
Encapsulation
Encapsulation is a mechanism that allows us to bind data and functions of a class into an entity.
It protects data and functions from outside interference and misuse. Therefore, it also provides
security. A class is the best example of encapsulation.
Inheritance
The concept allows us to inherit or acquire the properties of an existing class (parent class) into a
newly created class (child class). It is known as inheritance. It provides code reusability.
Polymorphism
The word polymorphism is derived from the two words i.e. ploy and morphs. Poly means many
and morphs means forms. It allows us to create methods with the same name but different
method signatures. It allows the developer to create clean, sensible, readable, and resilient code.
The above figure best describes the concepts of polymorphism. A person plays an employee role
in the office, father and husband role in the home.
The major concepts that we have discussed above are known as pillars of OOPs. There
are four pillars on which OOP rests.
o Abstraction
o Encapsulation
o Inheritance
o Polymorphism
Benefits of OOP
o Modular, scalable, extensible, reusable, and maintainable.
o It models the complex problem in a simple structure.
o Object can be used across the program.
o Code can be reused.
o We can easily modify, append code without affecting the other code blocs.
o Provides security through encapsulation and data hiding features.
o Beneficial to collaborative development in which a large project is divided into groups.
o Debugging is easy.
There are various object-oriented programming languages are present. They are Java, C+
+, C#, Python, R, PHP, Visual Basic.NET, JavaScript, Ruby, Perl, Object Pascal, Objective-
C, Dart, Swift, Scala, Kotlin, Common Lisp, MATLAB, and Smalltalk.
Features of Java
The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features which
play an important role in the popularity of this language. The features of Java are also known as
Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
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
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language.
A platform is the hardware or software environment in which a program runs.
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
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).
S.no. On the Procedural Programming Object-oriented programming
basis of
6. Access There are no access modifiers in The access modifiers in OOP are
modifiers procedural programming. named as private, public, and
protected.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
JVM is:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the classloader. There are three built-in classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes, java.util
package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader
of System classloader. It loades the jar files located inside
$JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader.
It loads the classfiles from classpath. By default, classpath is set to current directory. You
can change the classpath using "-cp" or "-classpath" switch. It is also known as
Application classloader.
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null
These are the internal classloaders provided by Java. If you want to create your own classloader,
you need to extend the ClassLoader class.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack
7) Execution Engine
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts
of the byte code that have similar functionality at the same time, and hence reduces the
amount of time needed for compilation. Here, the term "compiler" refers to a translator
from the instruction set of a Java virtual machine (JVM) to the instruction set of a
specific CPU.
Java Native Interface (JNI) is a framework which provides an interface to communicate with
another application written in another language like C, C++, Assembly etc. Java uses JNI
framework to send output to the Console or interact with OS libraries.
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.
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
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:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
1 What is a class in Java
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
class Student
{
int id;
String name;
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Save : Student.java
Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into
byte code.
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.
class Student
{
int id;
String name;
}
class TestStudent1
{
public static void main(String
args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Save: TestStudent1.java
1 What is an object in Java
An entity that has state and behavior is known as an object. It can be physical or logical (tangible
and intangible).
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Object Definitions:
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.
An object has three characteristics:
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Save: TestStudent2.java
2) Object and Class Example: Initialization through method
In this type, we are creating the two objects of Student class and initializing the value to these
objects by invoking the insertRecord method. Here, we are displaying the state (data) of the
objects by invoking the displayInformation() method.
class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Save: TestStudent4.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.
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the
memory location. It is a combination of "vary + able" which means its value can be changed.
Declaring a Variable
In Java, all variables must be declared before they can be used.
type identifier [ = value][, identifier [= value] ...] ;
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 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.
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}
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:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
additive +-
equality == !=
bitwise ^
exclusive OR
bitwise |
inclusive OR
logical OR ||
Ternary ternary ?:
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
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
Let's understand the if-statements one by one.
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.
if(condition)
{
statement 1; //executes when condition is true
}
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.
if(condition)
{
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
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.
if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else
{
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when all the conditions are false
}
}
}
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.
if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when condition 2 is false
}
}
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.
*Note:
1. The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
2. Cases cannot be duplicate
3. Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
4. Break statement terminates the switch block when the condition is satisfied. It is optional, if
not used, next case is executed.
5. While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Loop Statements
if 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.
Loops are three types , They are
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.
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.
for(initialization, condition, increment/decrement)
{
//block of statements}
}
while loop
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.
Initialization
while(condition)
{
//looping statements
increment/decrement
}
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.
Initialization;
do
{
//statements
increment/decrement;
} while (condition);
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.
1. break statement
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.
BreakExample.java
public class BreakExample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++)
{
System.out.println(i);
if(i==6)
{
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
2 Continue statement
The continue statement doesn't break the loop, whereas, it skips the specific part of the loop and
jumps to the next iteration of the loop immediately.
public class ContinueExample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
}
}
Output:
0
1
2
3
5
Enums
An enum is a special "class" that represents a group of constants (unchangeable variables, like
final variables).
Java Enums can be thought of as classes which have a fixed set of constants (a variable that does
not change). The Java enum constants are static and final implicitly. It is available since JDK 1.5.
Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is more
powerful. Here, we can define an enum either inside the class or outside the class.
Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods in
Java enum.
enum Level {
LOW,
MEDIUM,
HIGH
}
access enum constants with the dot syntax:
Level myVar = Level.MEDIUM;
Example 1:
class EnumExample1{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}
Output:
WINTER
SPRING
SUMMER
FALL
Example 2
class EnumExample1{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//creating the main method
public static void main(String[] args) {
//printing all enum
for (Season s : Season.values()){
System.out.println(s);
}
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal());
}}
Output:
WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Example 3:
enum Level {
LOW,
MEDIUM,
HIGH
}
switch(myVar) {
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
}
}
}
Output:
Medium level
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into
primitives automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.
Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it
will not change the original value. But, if we convert the primitive value in an object, it will
change the original value.
Serialization: We need to convert the objects into streams to perform the serialization. If we
have a primitive value, we can convert it in objects through the wrapper classes.
Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.
Method Description
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Program to add two non-integer numbers
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
double num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.print("Enter First Number: ");
num1 = sc.nextDouble();
sc.close();
sum = num1 + num2;
System.out.println("Sum of "+num1+" and "+num2+" is: "+sum);
}
}
Java Console Class
The Java Console class is be used to get input from console. It provides methods to read texts
and passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
String text=System.console().readLine();
System.out.println("Text is: "+text);
Method Description
Reader reader() It is used to retrieve the reader object associated with the console
String readLine() It is used to read a single line of text from the console.
char[] readPassword() It is used to read password that is not being displayed on the
console.
Console format(String fmt, It is used to write a formatted string to the console output stream.
Object... args)
Console printf(String format, It is used to write a string to the console output stream.
Object... args)
PrintWriter writer() It is used to retrieve the PrintWriter object associated with the
console.
import java.io.Console;
class ReadStringTest
{
public static void main(String args[])
{
Console c=System.console();
Java Dates
Java does not have a built-in Date class, but we can import the java.time package to work with
the date and time API. The package includes many date and time classes. For example:
Class Description
LocalDate Represents a date (year, month, day (yyyy-MM-dd))
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.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to
use the sizeof operator.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the loop.
syntax:
for(data_type variable:array){
//body of the loop
}
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
10
22
44
66
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the
array in negative, equal to the array size or greater than the array size while traversing the array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you mightexpect, look
and act like regular multidimensional arrays. However, as you will see there are a couple of
subtle differences. To declare a multidimensional array variable,specify each additional index
using another set of square brackets. For example, the following declares a two-dimensional
array variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an
array of arrays of int.
// Demonstrate a two-dimensional array.
class Overload {
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Ex2
class OverloadDemo
{
void test()
{
int a=5,b=6,c;
c=a+b;
System.out.println("No parameters "+c+"\n");
}
class Overload {
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
}
}
Constructor overloading
Ex1
class Box {
double width; double height; double depth;
// This is the constructor for Box.
Box()
{
width = -1;
height = -1;
depth = -1;
}
}
class BoxDemo
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
double vol;
Call by reference means we call a method by passing reference (location of the variable) in a
parameter. In Java, primitive data types (Int, float, double, Boolean, char, etc.) are always passed
as values and Non-Primitive data types (class, object, array, string, and interface) are always
passed as a reference.
2. Call by Reference
Ex1
class CaRef
{
int data=50;
void change(CaRef op)
{
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[])
{
CaRef op=new CaRef ();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
Ex2
class Test {
int a, b;
Test(int i, int j) {
a = i; b = j;
}
// pass an object
void meth(Test o)
{
o.a*= 2;
o.b/= 2;
}
}
class PassObjRef {
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}
Recursive Ex1
➢ Java supports recursion.
➢ Recursion is the process of defining something in terms of itself.
➢ A method that calls itself is said to be recursive.
➢ When a method calls itself, new local variables and parameters are allocated storage on the
stack, and the method code is executed with these new variables from the start.
➢ As each recursive call returns, the old local variables and parameters are removed from the
stack.
➢ The main advantage to recursive methods is that they can be used to create clearer and simpler
versions of several algorithms than can their iterative relatives. Ex: QuickSort and AI related
problems
➢ When writing recursive methods, we must have an if statement somewhere to force the
method to return without the recursive call being executed.
➢ Recursive versions of many routines may execute a bit more slowly than the iterative
equivalent because of the added overhead of the additional method calls.
class Factorial
{
// this is a recursive method
int fact(int n)
{
int fact;
if(n==1)
return 1;
else
{
fact = fact(n-1) * n;
return fact;
}
}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
ACCESS CONTROL METHODS / ACCESS MODIFIERS IN JAVA
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private access modifier is accessible only within the class.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
In the above example, we created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
4) Public The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
This Reference
*this keyword
this always refers to the currently executing object.
There are two uses with the this keyword.
1. To resolve the name collisions between instance variables and local variables
2. To explicitly call a constructor from another constructor
class HelloWorld
{
int sno;
String sname;
HelloWorld(int sno,String sname)
{
this.sno=sno;
this.sname=sname;
}
public static void main(String[] args)
{
HelloWorld h=new HelloWorld(10,"ABC");
System.out.println(h.sno+" "+h.sname);
a) We can use this to call a constructor from another constructor. This is called a Explicit
constructor invocation.
b) this() should be the first statement inside a constructor.
class Box
{
double width; double height; double depth;
Box()
{
System.out.println("Defualt constructor");
}
// This is the constructor for Box.
Box(double w,double h, double d)
{
// calling default constructor this();
System.out.println("Constructing Box"); width = 10;
height = 10;
depth = 10;
}
}
Garbage Collection
➢ In Java, objects are allocated memory dynamically using new operator. But memory de-
allocation happens automatically.
➢ In Java, Garbage collection is the technique through which the memory de-allocation will
happen automatically.
Working of Garbage Collection
a) The job of the Garbage collector is to identify the unused objects and delete them from
memory.
b) Garbage collector checks the objects which do not have any reference and deletes them from
memory.
c) Garbage collector runs periodically during the program execution. But there is no guarantee
when a Garbage collector runs.
d) The garbage collector runs periodically, checking for objects that are no longer referenced by
any running state or indirectly through other referenced objects.
e) Garbage collector calls finalize( ) method just before it runs.
gc() method
1. The gc() method is used to invoke the garbage collector to perform cleanup processing.
2. The gc() is found in System and Runtime classes.
public static void gc(){ }
Example
public class MemoryTest
{
public static void main(String args[])
{
Runtime r=Runtime.getRuntime();
System.out.println("Total Memory: "+r.totalMemory());
System.out.println("Free Memory: "+r.freeMemory());
for(int i=0;i<100;i++)
{
new MemoryTest();
}
System.out.println("After creating 100 instance, Free Memory: "+r.freeMemory());
System.gc();
System.out.println("After gc(), Free Memory: "+r.freeMemory());
}
}
finalize( ) method / finalization
a) By using finalize() method or finalization, we can define specific actions that will occur when
an object is just about reclaimed by the Garbage collector.
b) To add a finalizer to a class, we simply define the finalize( ) method. The Java run time calls
that method whenever it is about to recycle an object of that class.
c) Inside the finalize( ) method, you will specify those actions that must be performed before an
object is destroyed.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Static
Static is used to access a member by itself, without reference to a specific instance. When a
member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object.
Things can be declared as static
1. Variables
2. Methods
3. Static blocks
4. Nested classes
Things cannot be declared as static
1. Local variables
2. classes
3. constructor
static variables (class variables)
➢ Instance variables declared as static are, essentially, global variables.
➢ When objects of its class are declared, no copy of a static variable is made.
➢ Instead, all instances of the class share the same static variable.
static methods
Methods declared as static have several restrictions:
➢ They can only directly call other static methods.
➢ They can only directly access static data.
➢ They cannot refer to this or super in any way.
Static blocks (OR) static initialization block
➢ Static blocks are used to initialize the static variables.
➢ Static block gets executed exactly once, when the class is first loaded.
// Demonstrate static variables, methods, and blocks.
1. Inner class
➢An inner class is a non-static nested class.
➢It has access to all of the variables and methods of its outer class, including private members
➢We can create an instance of an Inner class only through the object of the outer class.
String Methods
Important methods in the String class
1. charAt() Returns the character located at the specified index
2. concat() Appends one String to the end of another ( "+" also works)
3. equalsIgnoreCase() Determines the equality of two Strings, ignoring case
4. length() Returns the number of characters in a String
5. replace() Replaces occurrences of a character with a new character
6. substring() Returns a part of a String
7. toLowerCase() Returns a String with uppercase characters converted
8. toString() Returns the value of a String
9. toUpperCase() Returns a String with lowercase characters converted
10. trim() Removes whitespace from the ends of a String
1. public char charAt(int index)
String x = “CARGO";
System.out.println( x.charAt(2) ); Output is : R
2. public String concat(String s)
String x = "taxi";
System.out.println( x.concat(" cab") ); Output is : taxi cab
+ and += operators
String x = "library";
System.out.println( x + " card"); Output is : library card
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
Constructor Description
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
String Buffer is Mutable Ex:
class HelloWorld {
public static void main(String[] args) {
StringBuffer s=new StringBuffer("Hello");
s.append(" VBIT");
System.out.println(s);
}
}
Example:
// Display all command-line arguments.
class CommandLine
{
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
javac CommandLine.java
java CommandLine this is a test 10 -20
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1