2 Java Programming 1
2 Java Programming 1
UNIT-1
Java Introduction
Programming language
A programming language is a formal language that specifies a set of instructions that can
be used to produce various kinds of output. Programming languages generally consist
ofinstructions for a computer. Programming languages can be used to create programs that
implement specific algorithms.
Machine language is the lowest and most elementary level of programming language and was the
first type of programming language to be developed. Machine language is basically the only
language that a computer can understand and it is usually written in hex.In fact, a manufacturer
designs a computer to obey just one language, its machine code, which is represented inside the
computer by a string of binary digits (bits) 0 and 1. The symbol 0 stands for the absence of an
electric pulse and the 1 stands for the presence of an electric pulse. Since a computer is capable
of recognizing electric signals, it understands machine language.
Advantages:
Fast execution 2.It requires no translator to translate the code. It is directly understood by the
computer
Disadvantages:
1. Programs had to be written using binary codes unique to each computer.
2. Programmers had to have a detailed knowledge of the internal operations of the specific type
of CPU they were using.
3. Programming was difficult and error-prone
4. Programs are not portable to other computers.
Assembly language
Assembly language was developed to overcome some of the many inconveniences of machine
language. This is another low-level but very important language in which operation codes and
operands are given in the form of alphanumeric symbols instead of 0’s and l’s.
These alphanumeric symbols are known as mnemonic codes and can combine in a maximum of
five-letter combinations e.g. ADD for addition, SUB for subtraction, START, LABEL etc.
Because of this feature, assembly language is also known as ‘Symbolic Programming Language.'
Advantages:
1. Uses symbolic coded instructions which are easier to remember
2. Programming is simplified as a programmer does not need to know the exact storage location
of data and instructions.
3. Efficient use of computer resources is out weighted by the high costs of very tedious systems
development and by lock of program portability.
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 most important features of Java language is given below.
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
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
incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
1. Basic concepts of OOPs are:
2. Object
3. Class
4. Inheritance
5. Polymorphism
6. Abstraction
7. 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 the top of other hardware-based platforms. It has two components:
• Runtime Environment
• API(Application Programming Interface)
Java code can be run 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:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
• 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
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-
C++ Java
C++ is mainly used for system Java is mainly used for application programming.
programming. It is widely used in window, web-based, enterprise
and mobile applications.
C++ was designed for systems and Java was designed and created as an interpreter for
applications programming. It was an printing systems but later extended as a support network
extension of C programming language. computing. It was designed with a goal of being easy to use
and accessible to a broader audience.
C++ supports the goto statement. Java doesn't support the goto statement.
C++ supports multiple inheritance. Java doesn't support multiple inheritance through class.
It can be achieved by interfaces in java.
C++ supports pointers. You can write Java supports pointer internally. However, you can't write
pointer program in C++. the
pointer program in java. It means java has restricted pointer
support in java.
C++ uses compiler only. C++ is Java uses compiler and interpreter both. Java source code is
compiled and run using the compiler converted into bytecode at compilation time. The
which converts source code into machine interpreter
code so, C++ is platform dependent. executes this bytecode at runtime and produces output.
Java is
interpreted that is why it is platform independent.
C++ supports both call by value and call Java supports call by value only. There is no call by
by reference. reference in java.
C++ supports structures and unions. Java doesn't support structures and unions.
C++ doesn't support documentation Java supports documentation comment (/** ... */) to create
comment. documentation for java source code.
C++ supports virtual keyword so that we Java has no virtual keyword. We can override all non-static
can decide whether or not override a methods by default. In other words, non-static methods are
function. virtual by default.
C++ doesn't support >>> operator. Java supports unsigned right shift >>> operator that fills
zero at the top for the negative numbers. For positive
numbers, it works same like >> operator.
C++ creates a new inheritance tree Java uses a single inheritance tree always because all
always. classes are the child of Object class in java. The object
class
is the root of the inheritance tree in java.
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:
➢ Standard Edition Java Platform
➢ Enterprise Edition Java Platform
➢ Micro Edition Java Platform
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.
Super Class: The class whose features are inherited is known as superclass(or a base class or a
parent class).
Sub Class: The class that inherits the other class is known as subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our
new class from the existing class. By doing this, we are reusing the fields and methods of the
existing class.
The keyword used for inheritance is extends.
Syntax:
class derived-class extends base-class
{
//methods and fields
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.It is called instance variable because its value is instance
specific and is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation
for static variable happens only once when the class is loaded in the memory.
Example to understand the types of variables in java
class A{
int data=50;//instance variable
\n Newline (0x0a)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\\ backslash
Byte 0 1 byte
Int 0 4 byte
Long 0L 8 byte
String Length
A String in Java is actually an object, which contain methods that can perform certain operations
on strings. For example, the length of a string can be found with the length() method:
Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
Note that we have added an empty text (" ") to create a space between firstName and lastName
on print.
You can also use the concat() method to concatenate two strings:
Example
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
Special Characters
Because strings must be written within quotes, Java will misunderstand this string, and generate
an error:
String txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
\\ \ Backslash
\t Tab Try it »
\b Backspace Try it »
\f Form Feed
Operators in Java
Operator in Java is a symbol which is used to perform operations.
For example: +, -, *, / etc.
Types of operators
• Unary Operator,
• Arithmetic Operator,
• Shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
• incrementing/decrementing a value by one
• negating an expression
• inverting the value of a boolean
Example1: ++ and --
class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10
Arithmetic Operators
• Java arithmatic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Assignment Operator
Java assignment operator is one of the most common operator. It is used to assign the value on
its right to the operand on its left.
Example
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Output:
14
16
constant
• A constant is a variable whose value cannot change once it has been assigned. Java
doesn't have built-in support for constants.
• A constant can make our program more easily read and understood by others. In addition,
a constant is cached by the JVM as well as our application, so using a constant can
improve performance.
• To define a variable as a constant, we just need to add the keyword “final” in front of the
variable declaration.
Syntax
if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}
Example
public class Test {
public static void main(String args[]) {
int x = 30;
if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
} }}
Output
This is else statement
Syntax
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
Example
public class Test {
public static void main(String args[]) {
int x = 30;
if( x == 10 ) {
System.out.print("Value of X is 10");
}else if( x == 20 ) {
System.out.print("Value of X is 20");
}else if( x == 30 ) {
System.out.print("Value of X is 30");
}else {
System.out.print("This is else statement");
} }}
Output
Value of X is 30
Nested if statement
It is always legal to nest if-else statements which means you can use one if or else if statement
inside another if or else if statement.
Syntax
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
public class Test {
public static void main(String args[]) {
int x = 30;
int y = 10;
Output
X = 30 and Y = 10
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
// You can have any number of case statements.
default : // Optional
// Statements
}
Syntax
while(Boolean_expression)
{
// Statements
}
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non zero value.
Flow Diagram
Example
public class Test {
do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}}
This will produce the following result −
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
Syntax
for(initialization; Boolean_expression; update)
{
// Statements
}
Here is the flow of control in a for loop −
• The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables and this step ends with a semi colon (;).
• Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed.
If it is false, the body of the loop will not be executed and control jumps to the next
statement past the for loop.
• After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank with a semicolon at the end.
• The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Example
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x + 1) {
System.out.print("value of x : " + 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
Syntax
break;
Flow Diagram
Example
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
} }}
Output
10
20
Continue statement
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
• In a for loop, the continue keyword causes control to immediately jump to the update
statement.
Flow Diagram
Example
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
} }}
Output
10
20
40
50
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.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. 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.
3. 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.
4. 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.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Example
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
} }
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides more
accessibility than private. But, it is more restrictive than protected, and public.
Example
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
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
} }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
Example of public access modifier
//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();
• Information can be passed to methods as parameter. Parameters act as variables inside the
method.
• Parameters are specified after the method name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma.
• The following example has a method that takes a String called fname as parameter.
When the method is called, we pass along a first name, which is used inside the method
to print the full name:
Example
MyClass.java
public class MyClass {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
OUTPUT
Liam Refsnes
Jenny Refsnes
Anja Refsnes
When a parameter is passed to the method, it is called an argument. So, from the example
above: fname is a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters
MyClass.java
Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
Example
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
} }
Output:
Bike is created
Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
Example
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.
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
Syntax
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:
Example
import java.util.Scanner;
• In the example above, java.util is a package, while Scanner is a class of
the java.util package.
• To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:
Example
Using the Scanner class to get user input:
import java.util.Scanner;
class MyClass
{ public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String userName = myObj.nextLine();
System.out.println("Username is: " + userName);
Method Overloading
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.
Three ways to overload a method
In order to overload a method, the argument lists of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
Although Java is strictly pass by value, the precise effect differs between whether a primitive
type or a reference type is passed.
When we pass a primitive type to a method, it is passed by value. But when we pass an object to
a method, the situation changes dramatically, because objects are passed by what is effectively
call-by-reference. Java does this interesting thing that’s sort of a hybrid between pass-by-value
and pass-by-reference. Basically, a parameter cannot be changed by the function, but the
function can ask the parameter to change itself via calling some method within it.
• While creating a variable of a class type, we only create a reference to an object. Thus,
when we pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
this keyword
In Java, this is a keyword which is used to refer current object of a class. we can it to refer any
member of the class. It means we can access any instance variable and method by
using this keyword.The main purpose of using this keyword is to solve the confusion when we
have same variable name for instance and local variables.We can use this keyword for the
following purpose.
• this keyword is used to refer to current object.
• this is always a reference to the object on which method was invoked.
• this can be used to invoke current class constructor.
• this can be passed as an argument to another method.
Example:
class Demo
{
Double width, height, depth;
Demo (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
public static void main(String[] args) {
Demo d = new Demo(10,20,30);
System.out.println("width = "+d.width);
System.out.println("height = "+d.height);
System.out.println("depth = "+d.depth); }}
OUTPUT
width = 10.0
height = 20.0
depth = 30.0
Enumeration
• Enumerations serve the purpose of representing a group of named constants in a
programming language. For example the 4 suits in a deck of playing cards may be 4
enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type
named Suit. Other examples include natural enumerated types (like the planets, days of
the week, colors, directions, etc.).
Enums are used when we know all possible values at compile time, such as choices on a
menu, rounding modes, command line flags, etc. It is not necessary that the set of
constants in an enum type stay fixed for all time.
• In Java (from 1.5), enums are represented using enum data type. Java enums are more
powerful than C/C++ enums . In Java, we can also add variables, methods and
constructors to it. The main objective of enum is to define our own data
types(Enumerated Data Types).
Declaration of enum in java :
Enum declaration can be done outside a Class or inside a Class but not inside a Method.
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
Text Book
1. S.Sagayaraj, R.Denis, P.Karthik & D.Gajalakshmi, “Java Programming“, Universities Press,
2017
References
1. Patrick Naughton and Herbert Schildt. “The Complete Reference JAVA 2”. 3rd Edition. Tata
McGraw-Hill Edition, 1999.
2. Muthu C. “Programming with JAVA”. 2nd Edition. Vijay Nicole Imprints, 2011.
3. Ken Arnold Gosling and Davis Holmen. “The Java Programming Language”. 3rd Edition.
Addition Wesley Publication.