Unit-I Notes - Java
Unit-I Notes - Java
Java Programming
(A study material for M.C.A First Year)
Compiled by
Dr. M.Sivasakthi Ph.D., NET
USA20301J - PROGRAMMING IN JAVA
Unit-I Notes
When the chronicle of computer languages is written, the following will be said: B led to
C, C evolved into C++, and C++ set the stage for Java.
Java is related to C++, which is a direct descendent of C. Much of the character of Java
is inherited from these two languages. From C, Java derives its syntax. Many of Java's
Object-oriented features were influenced by C++.
Birth of C programming
The creation of Java: Java was conceived by James Gosling, Patrick Naughton, Chris Warth,
Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop
the first working version. This language was initially called "Oak" but was renamed "Java" in
1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement
of Java in the spring of 1995.
The trouble with C and C++ (and most other languages) is that they are designed to be compiled
for a specific target. Although it is possible to compile a C++ program for just about any type of
CPU, to do so requires a full C++ compiler targeted for that CPU. The problem is that compilers
are expensive and time-consuming to create. An easier—and more cost-efficient—solution was
needed. In an attempt to find such a solution, Gosling and others began work on a portable,
2|Page
platform-independent language that could be used to produce code that would run on a variety of
CPUs under differing environments. This effort ultimately led to the creation of Java.
Java has had a profound effect on the Internet. The reason for this is quite simple: Java expands
the universe of objects that can move about freely in cyberspace. In a network, two very broad
categories of objects are transmitted between the server and your personal computer:
i) Passive information
ii) Dynamic, active programs.
For example, when you read your e-mail, you are viewing passive data. Even when you
download a program, the program's code is still only passive data until you execute it. However,
a second type of object can be transmitted to your computer: a dynamic, self-executing program.
Such a program is an active agent on the client computer, yet is initiated by the server. For
example, a program might be provided by the server to display properly the data that the server is
sending.
As desirable as dynamic, networked programs are, they also present serious problems in the
areas of security and portability. Prior to Java, cyberspace was effectively closed to half the
entities that now live there. As you will see, Java addresses those concerns and, by doing so, has
opened the door to an exciting new form of program: the applet.
Java can be used to create two types of programs: applications and applets. An application is a
program that runs on your computer, under the operating system of that computer. An applet is
an application designed to be transmitted over the Internet and executed by a Java-compatible
Web browser
3|Page
Java's Magic: The Bytecode
output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly
optimized set of instructions designed to be executed by the Java run-time system, which is
called the Java Virtual Machine (JVM).
Translating a Java program into bytecode helps makes it much easier to run a program in
a wide variety of environments.
The fact that a Java program is interpreted also helps to make it secure. Because the execution of
every Java program is under the control of the JVM.
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
4|Page
• Dynamic
Architecture-neutral- no guarantee exists that if you write a program today, it will run
tomorrow—even on the same machine. Operating system upgrades, processor upgrades, and
changes in core system resources can all combine to make a program malfunction. The Java
designers made several hard decisions in the Java language and the Java Virtual Machine in an
attempt to alter this situation. Their goal was "write once; run anywhere, any time, forever."
Interpreted- Java bytecode can be interpreted on any system that provides a Java Virtual
Machine.
High performance- Java bytecode was carefully designed so that it would be easy to translate
directly into native machine code for very high performance by using a just-in-time compiler.
5|Page
Distributed - Java is designed for the distributed environment of the Internet, because it handles
TCP/IP protocols. Java has revived a package called Remote Method Invocation (RMI).
Dynamic - Java programs carry with them substantial amounts of run-time type information that
is used to verify and resolve accesses to objects at run time.
Evolution of Java
History of Java.
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.
6|Page
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
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.
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.
7|Page
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (to be released by March 2022)
8|Page
being accessed by the code outside this shield.
Encapsulation can be achieved by declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables.
Example:
Example:
int length;
int breadth;
9|Page
public void getArea() {
int area = length * breadth;
System.out.println("Area: " + area);
}}
class Main {
public static void main(String[] args) {
Polymorphism
The word “poly” means many and “morphs” means forms, So it means many forms. we can define
polymorphism as the ability to take more than one form. For Example a person at the same time can
have different characteristics. Like a man at the same time is a father, a husband, an employee. So the
same person possesses different behavior in different situations. This is called polymorphism.
Example
10 | P a g e
Example:
Types of polymorphism
Example
// Class 1
// Helper class
class Helper {
11 | P a g e
// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Class 2
// Main class
class GFG {
Output:
8
42
Runtime Polymorphism
12 | P a g e
It is also known as Dynamic Method Dispatch. It is a process in which a function call to the
overridden method is resolved at Runtime. This type of polymorphism is achieved by Method
Overriding. Method overriding, on the other hand, occurs when a derived class has a definition for
one of the member functions of the base class. That base function is said to be overridden.
Example:
// Class 1
// Helper class
class Parent {
13 | P a g e
// Print statement
System.out.println("subclass2");
}
}
// Class 4
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of class 1
Parent a;
// Now we will be calling print methods
// inside main() method
a = new subclass1();
a.Print();
a = new subclass2();
a.Print();
}
}
Output:
subclass1
subclass2
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object.
Example:
14 | P a g e
The reason for using inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Terminologies
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
15 | P a g e
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
16 | P a g e
Types of inheritance in java
Lexical Issues
17 | P a g e
Whitespace
program could have been written all on one line or in any other strange way you felt like typing it, as long as there
was at least one whitespace character between each token that was not already delineated by an operator or
separator. In Java, whitespace is a space, tab, or newline.
Identifiers
Identifiers are used for class names, method names, and variable names. An identifier may be any descriptive
sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters. They must not
begin with a number, lest they be confused with a numeric literal. Again, Java is case-sensitive, so VALUE is a
different identifier than Value.
2count
high temp
Not/ok
Literals
A constant value in Java is created by using a literal representation of it. For example,
here are some literals: 100 98.6 'X' "This is a test"
Comments
18 | P a g e
there are three types of comments defined by Java. You have already seen two: single-line and multiline. The third
type is called a documentation comment. This type of comment is used to produce an HTML file that documents
your program. The documentation comment begins with a /** and ends with a */.
Separators
In Java, there are a few characters that are used as separators. The most commonly
Keywords
Keywords are the reserved word These keywords cannot be used as names for a variable,
class, or method.
DATA TYPES
Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float,double, and
boolean. These can be put in four groups:
19 | P a g e
Integers This group includes byte, short, int, and long, which are for whole valued signed numbers.
Floating-point numbers This group includes float and double, which represent numbers with fractional precision.
Characters This group includes char, which represents symbols in a character set, like letters and numbers.
Boolean This group includes boolean, which is a special type for representing true/false values.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers. Many other Computer
languages, including C/C++, support both signed and unsigned integers.
byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128to
127. Variables of type byte are especially useful when you’re a network or file. They are also
usefulnotbe when directly compatible-intypeswith. Java’s other built
Syntax: byte b, c;
short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used Java
type, since it is defined as having its high byte first (called big-endian format). This type is mostly
applicable to 16-bit computers, which are becoming increasingly scarce.
Here are some examples of short variable declarations: short s;
short t;
20 | P a g e
int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from –
2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays. Any time you have an integer expression involving
bytes, shorts, ints, and literal numbers, the entire expression Is promoted to int before the
calculation is done.
long
long is a signed 64-bit type and is useful for those occasions where an int type is notlarge enough to
hold the desired value. The range of a long is quite large. This makesit useful when big, whole
numbers are needed. For example, here is a program thatcomputes the number of miles that light will
travel in a specified number of days.
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional
precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value
whose precision requires a floating-point type.
float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some
processors and takes half as much space as double precision, but will become imprecise when the values are either
very large or very small.
21 | P a g e
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually
faster than single precision on some modern processors that have been optimized for high-speed mathematical
calculations.
Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in Java is not the
same as char in C or C++. In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java. Instead,
Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of
the characters found in all human languages.
in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of
characters known as ASCII still ranges from 0 to 127 as always,
Booleans
Java has a simple type, called boolean, for logical values. It can have only one of two possible values, true or false.
This is the type returned by all relational operators, such as a < b. boolean is also the type required by the
conditional expressions that govern the control statements such as if and for.
boolean b;
Variables
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
22 | P a g e
char x = 'x'; // the variable x has the value 'x'.
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the variable
is declared.
For example, here is a short program that computes the length of the hypotenuse of a
right triangle given the lengths of its two opposing sides:
Scope of a variable determines the area or a region of code where a variable is available to use.
Lifetime of a variable is defined by the time for which a variable occupies some valid space in the
system's memory. Scope determines the life of a variable. Life of a variable depends on the scope.
The scope defined by a method begins with its opening curly brace. However, if that method has parameters, they
too are included within the method's scope.
As a general rule, variables declared inside a scope are not visible (that is, accessible) to code that is defined outside
that scope. Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from
unauthorized access and/or modification. Indeed, the scope rules provide the foundation for encapsulation.
23 | P a g e
Scopes can be nested. Example for block scope
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Here is another important point to remember: variables are created when their scope is entered, and destroyed when
their scope is left. This means that a variable will not hold its value once it has gone out of scope. Therefore,
variables declared within a method will not hold their values between calls to that method. Also, a variable declared
within a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.
24 | P a g e
y is: -1
y is now: 100
y is: -1
y is now: 100
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
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Conditional Operators
Arithmetic Operators
25 | P a g e
-- Decrement Decreases the value of a variable by 1 --x
Relational Operators
== Equal to x == y
!= Not equal x != y
Logical Operators
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)
Bitwise Operators
& (bitwise Binary AND Operator copies a bit to the result (A & B) will give 12 which is
26 | P a g e
and) if it exists in both operands. 0000 1100
^ (bitwise Binary XOR Operator copies the bit if it is set (A ^ B) will give 49 which is
XOR) in one operand but not both. 0011 0001
Assignment Operators
= x=5 x=5
+= x += 3 x=x+3
27 | P a g e
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Conditional Operators
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide,
which value should be assigned to the variable.
Array
An array is a group of like-typed variables that are referred to by a common name. Arrays
of any type can be created and may have one or more dimensions. A specific element in
an array is accessed by its index.
One-Dimensional Arrays
28 | P a g e
The general form of a one dimensional array declaration is
type var-name[ ];
Example:
int month_days[];
Example:
month_days = new int[12];
Example Program
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
29 | P a g e
}
Multidimensional Arrays
Example Program
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
01234
30 | P a g e
56789
10 11 12 13 14
15 16 17 18 19
Control Statements
if Statement
Syntax:
if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}
Example
public class Test {
if( x < 20 ) {
System.out.print("This is if statement");
}
}
}
if-else statement
Syntax
if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}
Example
31 | P a g e
public class Test {
if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
}
}
Nested if
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}
}
Example
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}
}
32 | P a g e
}
}
Switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each case.
Syntax
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
break; // optional
Example
switch(grade) {
33 | P a g e
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Looping Statements
while loop
A while loop statement in Java programming language repeatedly executes a target statement as long
as a given condition is true.
while(Boolean_expression) {
// Statements
}
Example
public class Test {
while( x < 20 ) {
System.out.print("value of x : " + x );
34 | P a g e
x++;
System.out.print("\n");
}
}
}
Output:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be
executed a specific number of times.
for(initialization; Boolean_expression; update) {
// Statements
}
Example
public class Test {
35 | P a g e
}
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
do...while loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax
do {
// Statements
}while(Boolean_expression);
Example
public class Test {
do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
36 | P a g e
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Jumping Statements
In java, the break statement is used to terminate the execution of the nearest looping statement
or switch statement. The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.
Syntax:
break;
37 | P a g e
// break keyword in Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++) {
if (i == 6)
break;
System.out.println(i);
}
}
}
Output
0
1
2
3
4
5
Continue Statements
The continue statement pushes the next repetition of the loop to take place, hopping any code
between itself and the conditional expression that controls the loop.
class GFG {
38 | P a g e
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i == 6){
System.out.println();
// using continue keyword
// to skip the current iteration
continue;
}
System.out.println(i);
}
}
}
Output
0
1
2
3
4
5
7
8
9
return statement
A return statement causes the program control to transfer back to the caller of a method. Every
method in Java is declared with a return type and it is mandatory for all java methods. A return type
may be a primitive type like int, float, double, a reference type or void type(returns nothing).
Example
39 | P a g e
public class ReturnTypeTest2 {
public int add(int x, int y) { // with arguments
int z = x+y;
return z;
}
public static void main(String args[]) {
ReturnTypeTest2 test = new ReturnTypeTest2();
int add = test.add(10, 20);
System.out.println("The sum of x and y is: " + add);
}
}
Output
The sum of x and y is: 30
40 | P a g e