Java
Java
1.Explain OOP Concepts in Java. Explain the importance of Polymorphism, Encapsulation and Inheritance.
Object-Oriented Programming or OOPs refers to languages that uses objects in programming. Object-oriented programming aims to implement real-world
entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so
that no other part of the code can access this data except that function.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object: It is a basic unit of Object-Oriented Programming and represents the real-life entities. A typical Java program creates many objects, which as you know,
interact by invoking methods. An object consists of:
Example of an object: A dog is an object because it has states like color, name, breed, etc. as well as behaviours like wagging the tail, barking, eating, etc.
Class: Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space. In general, class declarations can include these components, in order:
Example:
Inheritance: When one object acquires all the properties and behaviours of a parent object, it is known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism. The keyword used for inheritance is extends. Important terminologies in inheritance include:
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.
Example:
Polymorphism: If one task is performed in different ways, it is known as polymorphism. Polymorphism refers to the ability of OOPs programming languages to
differentiate between entities with the same name efficiently. For example: to draw something, for example, shape, triangle, rectangle, etc. In Java, we use
method overloading and method overriding to achieve polymorphism.
Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple
implementations. The word “poly” means many and “morphs” means forms, so it means many forms.
Compile time polymorphism: It is also known as static polymorphism. This type of polymorphism is achieved by method overloading or operator
overloading.
1
Operator Overloading: Java also provide option to overload operators. For example, we can make the operator (‘+’) for string class to concatenate two
Page
strings. We know that this is the addition operator whose task is to add two operands. So, a single operator ‘+’ when placed between integer operands adds
them and when placed between string operands concatenates them.
Runtime polymorphism: 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.
Abstraction: Hiding internal details and showing functionality is known as abstraction. For example, by phone call, we don't know the internal processing. In
java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.
Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates.
Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield. A java class is
the example of encapsulation.
Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of
own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
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.
Features of Java
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.
Object-oriented
Java is an object-oriented programming language. Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
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. Java platform software environment in which a program runs. It has two components:
Runtime Environment
API (Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows, Linux, 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 separating the package for the classes of the local file system from those that are imported from network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to objects.
Security Manager: It determines what resources a class can access such as reading and writing to the local disk.
Robust
Robust simply means strong. Java is robust because:
It uses strong memory management.
There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application
anymore.
There are exception handling and the type checking mechanism in Java.
2
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed.
Page
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.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. 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 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).
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.
Its implementation is known as JRE (Java Runtime Environment).
Whenever you write java command on the command prompt to run the java class, an instance of JVM is created.
Loads code
Verifies code
Executes code
Provides runtime environment
JVM Architecture
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.
o Bootstrap ClassLoader
o Extension ClassLoader
o System/Application ClassLoader
Class(Method) Area : Class Area stores per-class structures such as the code for methods.
Program Counter Register : PC register contains the address of the Java virtual machine instruction currently being executed.
3
Page
Native Method Stack : It contains all the native methods used in the application.
Execution Engine : It contains:
o A virtual processor
o Interpreter: Read bytecode stream then execute the instructions.
o Just-In-Time (JIT) compiler: It is used to reduce the amount of time needed for compilation.
Java Native Interface: It is a framework which provides an interface to communicate with another application written in another language like C, C++, Assembly
etc.
Documentation Section
Package Statement
Import Statements
Interface Statement
Class Definition
Main Method Class
Documentation
You can write a comment in this section. Comments are beneficial for the programmer because they help them understand the code. These are optional, but we
suggest you use them because they are useful to understand the operation of the program, so you must write comments within the program.
/* comment_section */
Package Statement
You can create a package with any name. A package is a group of classes that are defined by a name. That is, if you want to declare many classes within one
element, then you can declare it within a package. It is an optional part of the program, i.e., if you do not want to declare any package, then there will be no
problem with it, and you will not get any errors. Here, the package is a keyword that tells the compiler that package has been created.
Syntax : package package_name;
Import Statement
This line indicates that if you want to use a class of another package, then you can do this by importing it directly into your program.
Syntax : import java.io.*;
Interface Statement
Interfaces are like a class that includes a group of method declarations. It's an optional section and can be used when programmers want to implement multiple
inheritances within a program.
Syntax : Interface interface_name { }
Class Definition
A Java program may contain several class definitions. Classes are the main and essential elements of any Java program.
Syntax : class class_name { }
The lexical structure of a programming language is a set of basic rules that specify how you write programs in this particular language.
A source code of a Java program consists of tokens. Tokens are atomic code elements. In Java we have comments, identifiers, literals, operators, separators, and
keywords.
Java programs are composed of characters from the Unicode character set.
1.Comments
Comments are used by humans to clarify source code. There are three types of comments in Java.
2.Java white space
White space in Java is used to separate tokens in the source file. It is also used to improve readability of the source code. The amount of space put between
tokens is irrelevant for the Java compiler. The white space should be used consistently in Java source code. Eg: int<space>i;
3.Java identifiers
Identifiers are names for variables, methods, classes, or parameters. Identifiers can have alphanumerical characters, underscores and dollar signs ($). It is an
error to begin a variable name with a number.
Identifiers are case sensitive. This means that Name, name, or NAME refer to three different variables. Identifiers also cannot match language keywords.
There are also conventions related to naming of identifiers. The names should be descriptive. We should not use cryptic names for our identifiers. If the name
consists of multiple words, each subsequent word is capitalized.
Eg:
4.Java literals
A literal is a textual representation of a particular value of a type. Literal types include Boolean, integer, floating point, string, null, or character. Technically, a
literal will be assigned a value at compile time, while a variable will be assigned at runtime.
5.Java operators
An operator is a symbol used to perform an action on some value. Operators are used in expressions to describe operations involving one or more operands.
There are different types of operators in Java.
Bitwise Operators: Bitwise operator works on bits and performs bit-by-bit operation.
Relational Operator: Relational operator operates on relationship that one operand has to the other.
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Java separators
A separator is a sequence of one or more characters. Following are the separators in Java:
() Parentheses Used to contain the lists of parameters in method definition and invocation. Also used for defining the precedence in
expressions, containing expressions in control statements, and surrounding cast types.
{} Braces Used to contains the values of automatically initialized arrays. Also used to define a block of code, for classes, methods,
and local scopes.
[] Brackets Used to declare array types. Also used when dereferencing array values.
; Semicolon Terminates the statements
, Comma Separates consecutive identifiers in a variable declaration. Also used to chain statements together inside a for statement
. Period Used to separate packages names from sub packages and classes. Also used to separate a variable or method from a
reference variable.
:: Colons Used to create a method or constructor reference
Java keywords
A keyword is a reserved word in Java language. Keywords are used to perform a specific task in the computer program. For example, to define variables, do
repetitive tasks or perform logical operations.
Java conventions
Conventions are best practices followed by programmers when writing source code. Each language can have its own set of conventions. Conventions are not
strict rules; they are merely recommendations for writing good quality code. Some of the conventions that are recognized by Java programmers are:
6.Explain Java variables. What is Dynamic initialization of Variables? What is the scope and lifetime of Java variables?
Variables in Java
The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition,
all the variables have a scope, which defines their visibility, and a lifetime.
6
In Java, all the variables must be declared before they can be used. The basic form of a variable declaration in Java is:
type identifier;
or,
type identifier = value;
or,
type identifier1, identifier2;
Instance Variables A variable which is declared inside a class and outside all the methods and blocks is an instance variable.
Class Variables A variable which is declared inside a class, outside all the blocks and is marked static is known as a class variable.
Local Variables All other variables which are not instance and class variables are treated as local variables including the parameters in a method.
class Sample
{
int x,y; //instance variables
static int result; //class variable
void add(int a, int b) //local variables
{
x=a;
y=b;
int sum=x+y; //sum is a local variable
System.out.println(“Sum is ”+sum);
}
public static void main(String args[])
{
Sample obj= new Sample();
obj.add(10,20);
}
}
Apart from using constants as initializer, Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.
For example, following is a short program that computes the length of the hypotenuse of a right-angle triangle given the lengths of its two opposing sides:
public class JavaProgram
{
public static void main(String args[])
{
/* c is dynamically initialized */
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Scope of a variable refers to in which areas or sections of a program can the variable be accessed, and lifetime of a variable refers to how long the variable stays
alive in memory. General convention for a variable’s scope is, it is accessible only within the block in which it is declared. A block begins with a left curly brace ‘{‘
and ends with a right curly brace ‘}’.
Scope of an instance variable is throughout the class except in static methods. Lifetime of an instance variable is until the object stays in memory.
7
Page
Scope of a class variable is throughout the class. Lifetime of a class variable is until the end of the program or as long as the class is loaded in memory.
Scope of a local variable is within the block in which it is declared. Lifetime of a local variable is until the control leaves the block in which it is declared.
A primitive data type specifies the size and type of variable values, and it has no additional methods.
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
Primitive types are predefined in Java. Non-primitive types are created by the programmer and is not defined by Java (except for String).
8
Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
Page
A primitive type has always a value, while non-primitive types can be null.
A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
The size of a primitive type depends on the data type, while non-primitive types have all the same size.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
8.What are Arrays? Explain the declaration of array variables. What are strings? Explain string manipulation functions in Java.
Java Arrays
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.
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.
Syntax:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Pointer to an Array
Syntax:
data_type (*var_name)[size_of_array];
Java supports the feature of an anonymous array, so you don't need to declare the array while passing an array to the method.
public class Test {
static void printArray(int arr[]){
---
}
public static void main(String args[]){
9
}}
Multidimensional Array in Java
In such case, data is stored in row and column-based index (also known as matrix form).
Java Strings
For example:
char[] ch={'t','e','s','t'};
String s=new String(ch);
O/P = test
The java.lang.String class provides a lot of methods to perform operations on strings. These are called String manipulation functions or accessor methods of
String class. Methods used to obtain information about an object are known as accessor methods.
concat()
length()
Str1.length()
indexOf()
str1.indexOf('S')
charAt()
str1.charAt(5)
contains()
returns either true or false by checking if the string contains the specified sequence of char values
str_Sample.contains("tar")
str1.toLowerCase()
str1.toUpperCase()
10
Page
MODULE II
Control statements are used to control the flow of execution of program based on certain conditions.
Conditional Control Statements allows the program to select between the alternatives during the program execution.
They are also called as decision-making statements or selection statements.
1. If statement
It will go inside the block only if the condition is true otherwise, it will not execute the block.
if(condition){
// statements (if Block)
}
//other statements
2. If-Else Statement
If the condition is true then, it will execute the If block. Otherwise, it will execute the Else block.
if(condition){
// statements (if Block)
}
else{
// statements (Else block)
}
//other statements
3. If Else-If statement
If the condition is true, then it will execute the If block. Otherwise, it will execute the Else-If block. Again, if the condition is not met, then it will move to the else
block.
if(condition){
// statements (if Block)
}
else if{
// statements (Else-If block)
}
else{
//statements(Else Block)
}//other statements
4. Switch Statement
Switch statement allows program to select one action among multiple actions during the program execution.
Switch(variable/value/expression) {
Case :
// statements [];
Case :
// statements [];
…
default:
// statements [];
}
Based on the argument in the switch statement suitable case value will be selected and executed.
11
These are used to execute a block of statements multiple times. It means it executes the same code multiple times so it saves code. These are also called
Iteration statements.
1. For loop
It executes the code until condition is false.
It is used when number of iterations are known.
2. While loop
While loop executes till the condition becomes false.
while(condition){
// statements
}
3. Do-while loop
When you are using for or while, then it will execute the loop body only if the condition if true.
In do-while loop, it will execute the loop first, then it checks the condition. So, it will execute the loop at least once.
It is called exit-controlled loop while for & while loop are called entry-controlled loop.
do{
// statements
}while(condition);
1. break Statement
It is used within any control statements. It is used to terminate the execution of the current loop or switch statements.
Syntax: break;
2. continue Statement
It is used to continue the execution of the current loop with the next iteration.
Syntax: continue;
Method
A method is a collection of statements that perform some specific task and return result to the caller. A method can perform some specific task without
returning anything. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class.
Method Declaration
Access Modifier: Defines access type of the method i.e. from where it can be accessed in your application. In Java, there 4 type of the access specifiers.
public: accessible in all class in your application.
protected: accessible within the package in which it is defined and in its subclasses (including subclasses declared outside the package).
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier): accessible within same class and package within which its class is defined.
The return type: The data type of the value returned by the method or void if does not return a value.
Method Name: the rules for field names apply to method names as well, but the convention is a little different.
Parameter list: Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no
parameters, you must use empty parentheses ().
Exception list: The exceptions you expect by the method can throw, you can specify these exception(s).
Method body: it is enclosed between braces. The code you need to be executed to perform your intended operations.
12
Eg:
public int max(int x, int y) { //method body }
Page
Method signature: It consists of the method name and a parameter list(without return type). Eg: max(int x, int y)
3.Can a class be static in Java?
Yes, we can have static class in java. In java, we have static instance variables as well as static methods and also static block. Classes can also be made static in
Java.
But,
Java allows us to define a class within another class. Such a class is called a nested class. The class which enclosed nested class is known as Outer class. In java,
we can’t make Outer class static. Only nested classes can be static.
Eg:
class Outercls{
private static String msg = "Welcome"; //should be static
public static class Nestedcls { //static class
public void printMessage() {
System.out.println("Message from nested static class: " + msg);
}
}
4.What is constructor? Explain different types of constructors with examples. Can a class have different constructor? (Constructor Overloading)
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.
We can use access modifiers while declaring a constructor. It controls the object creation. In other words, we can have private, protected, public or default
constructor in Java.
Default constructor
Parameterized constructor
Eg:
class Test{
Test(){ //default constructor
System.out.println("Success");
}
Eg:
class Test{
int id;
String name;
Test(int i, String n){ //parameterized constructor
id = i;
name = n;
}
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each
constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.
Page
Example of Constructor Overloading
class Test{
int id;
String name;
int age;
Test(int i, String n){ //creating two arg constructor
id = i;
name = n;
}
Test(int i, String n, int a){ //creating three arg constructor
id = i;
name = n;
age=a;
}
void display(){
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[]){
Test t1 = new Test(101,"John");
Test t2 = new Test(102,"Jerry",20);
t1.display();
t2.display();
} }
6.Explain method overloading and method overriding in Java with suitable examples. Distinguish between method overloading and method overriding.
Method Overloading
Method Overloading is a Compile time polymorphism. In method overloading, more than one method shares the same method name with different method
signature(parameters) in the class. In method overloading, return type can or cannot be the same, but we must have to change the parameter because in java,
we cannot achieve the method overloading by changing only the return type of the method.
Example of Overloading
class Test{
static int add(int a, int b){
return a+b;}
static int add(int a, int b, int c){
return a+b+c;}
public static void main(String args[]) {
System.out.println(add(4, 6));
System.out.println(add(4, 6, 7));
} }
O/P :
10
17
Method Overriding
Method Overriding is a Run time polymorphism. In method overriding, derived class provides the specific implementation of the method that is already
provided by the base class or parent class. In method overriding, return type must be same or co-variant (return type may vary in same direction as the derived
class).
Example of Overriding
class Animal{
void eat(){System.out.println("eating.");}
}
class Dog extends Animal{
void eat(){System.out.println("Dog is eating.");}
}
class Test{
public static void main(String args[]) {
Dog d1=new Dog();
Animal a1=new Animal();
d1.eat();
a1.eat();
} }
14
O/P :
Page
Dog is eating
eating
Difference between Method Overloading and Method Overriding in Java:
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviours of a parent object. It is an important part of OOPs (Object
Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.
Sub Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
Super Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
Here, the extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the
functionality.
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
15
Page
Single Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
O/P
barking...
eating...
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
O/P
weeping...
barking...
eating...
When two or more classes inherits a single class, it is known as hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
O/P
meowing...
16
eating...
Page
8.What are interfaces in Java? How multiple inheritance can be implemented in Java?
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction.
There can be only abstract methods in the Java interface, not method body.
It is used to achieve multiple inheritance in Java.
An interface is declared by using the interface keyword.
It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default.
A class that implements an interface must implement all the methods declared in the interface.
Syntax:
interface <interface_name> {
}
interface Printable{
void print();
}
class Test implements Printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
Test obj = new Test();
obj.print();
}
}
Output:
Hello
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class Test implements Printable,Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
Test obj = new Test();
obj.print();
obj.show();
}
}
Output:
Hello
17
Welcome
Page
9.What are abstract classes and methods in Java? Explain its uses. Write a program illustrating use of abstract classes and methods.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
There are two ways to achieve abstraction in java:
Abstract class (0 to 100%)
Interface (100%)
A method which is declared as abstract and does not have implementation is known as an abstract method.
Here, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by the Vehicle class.
Output:
running safely
Java Package
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
18
Page
Simple example of java package
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
} }
The -d switch specifies the destination where to put the generated class file. If you want to keep the package within the same directory, you can use . (dot).
Java <packagename>.<javafilename>
For example:
java mypack.Simple
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using package.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
//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();
} }
Output:Hello
2) Using package.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");
} }
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
19
} }
Page
Output:Hello
3) Using fully qualified name
If you use fully qualified name, then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
} }
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output:Hello
20
Page
MODULE III
1.What is Exception Hierarchy? What are the different types of Exceptions?
Exceptions in Java
An exception is an unwanted or unexpected event, which occurs during the execution of a program. In Java, an exception is an event that disrupts the normal
flow of the program. It is an object which is thrown at runtime.
The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java
Exception classes are given below:
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are
three types of exceptions:
Checked Exception
Unchecked Exception
Error
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
21
An Error indicates serious problem that a reasonable application should not try to catch. Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
Page
AssertionError etc.
2.Explain Exception handling in Java. Explain the uses of keywords try, catch and finally with examples. What is the difference between throw and throws?
The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so that normal flow of the application can be maintained.
The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application
that is why we use exception handling. Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will
not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.
Keyword Description
try The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be
followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception. It is used in the method body to throw an exception. “throw” is followed by an instance of
Exception class.
Eg: throw new ArithmeticException("Arithmetic Exception");
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the
method. It is always used with method signature. “throws” is followed by Exception class names.
Eg: throws ArithmeticException;
Whenever inside a method, if an exception has occurred, the method creates an Object known as Exception Object and hands it off to the run-time system
(JVM). The exception object contains name and description of the exception, and current state of the program where exception has occurred. Creating the
Exception Object and handling it to the run-time system is called throwing an Exception. There might be the list of the methods that had been called to get to
the method where exception was occurred. This ordered list of the methods is called Call Stack. Now the following procedure will happen.
The run-time system searches the call stack to find the method that contains block of code that can handle the occurred exception. The block of the code
is called Exception handler.
The run-time system starts searching from the method in which exception occurred, proceeds through call stack in the reverse order in which methods
were called.
If it finds appropriate handler, then it passes the occurred exception to it. Appropriate handler means the type of the exception object thrown matches
the type of the exception object it can handle.
If run-time system searches all the methods on call stack and couldn’t have found the appropriate handler then run-time system handover the Exception
Object to default exception handler, which is part of run-time system. This handler prints the exception information in the following format and
terminates program abnormally.
try {
// block of code to monitor for errors
}
catch (<Exception type1> <Exception object>) {
// exception handler for Exception type1
}
catch (<Exception type2> <Exception object>) {
// exception handler for Exception type2
22
}
finally { // optional
// block of code to be executed after try block ends
Page
}
Important points
In a method, there can be more than one statements that might throw exception, so put all these statements within its own try block and provide separate
exception handler within catch block for each of them.
If an exception occurs within the try block, that exception is handled by the exception handler associated with it. To associate exception handler, we must
put catch block after it. There can be more than one exception handlers. Each catch block is an exception handler that handles the exception of the type
indicated by its argument. The argument, ExceptionType declares the type of the exception that it can handle and must be the name of the class that
inherits from Throwable class.
For each try block there can be zero or more catch blocks, but only one finally block.
The finally block is optional. It always gets executed whether an exception occurred in try block or not. If exception occurs, then it will be executed
after try and catch blocks. And if exception does not occur then it will be executed after the try block. The finally block in java is used to put important
codes such as clean up code e.g. closing the file or closing the connection.
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code.
3.What are threads in Java? Explain multithreading. Explain thread life cycle.
Thread
A thread is a lightweight sub-process, the smallest unit of processing. All Java programs have at least one thread, known as the main thread, which is created by
the Java Virtual Machine (JVM) at the program’s start, when the main() method is invoked with the main thread.
In Java, creating a thread is accomplished by implementing an interface and extending a class. Every Java thread is created and controlled by
the java.lang.Thread class.
23
Page
Multithreading in Java
1. It doesn't block the user because threads are independent, and you can perform multiple operations at the same time.
2. You can perform many operations together, so it saves time.
3. Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
4. Threads share the same address space.
5. A thread is lightweight.
6. Cost of communication between the thread is low.
Creating a thread
Thread class
Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable
interface.
Output
24
thread is running...
Page
2) Java Thread Example by implementing Runnable interface
Output
thread is running...
A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Priority of a Thread
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread scheduler schedules the threads according to their
priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Page
Example of priority of a Thread
O/P:
running thread name is:Thread-0
running thread priority is:1
running thread name is:Thread-1
running thread priority is:10
1. Calling a start() on the thread when it's already executing run() method -:
When a thread is already running and executing its functions inside the run() method and amidst its execution, a call to the start() method on the same
thread, leads to an IllegalThreadStateException.
Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state
throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't
interrupt the thread but sets the interrupt flag to true.
Eg:
Output:
Exception handled
java.lang.InterruptedException: sleep interrupted
thread is running...
Synchronization in Java
26
Synchronization in java is the capability to control the access of multiple threads to any shared resource. Synchronization is a better option where we want to
Page
Types of Synchronization
Thread Synchronization
1. Mutual Exclusive
a) Synchronized method.
b) Synchronized block.
c) static synchronization.
2. Cooperation (Inter-thread communication in java)
Synchronization is built around an internal entity known as the lock or monitor. Every object has an lock associated with it. By convention, a thread that needs
consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.
Synchronized method
Eg:
class Table{
….
Synchronized block
Eg:
class Table{
….
Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Eg:
Without synchronization
class Table{
static void printTable(int n){
for(int i=1;i<=2;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
27
}
}
Page
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}}
t1.start();
t2.start();
}
}
O/P:
1
10
2
20
class Table{
t1.start();
t2.start();
}
}
O/P:
1
2
10
20
lock) in the same critical section to be executed. It is implemented by following methods of Object class:
wait()
Page
notify()
notifyAll()
MODULE IV
1.What are streams? Explain stream related classes in Java. Write an example for file I/O in Java using streams.
Stream Classes
In Java, a stream is a path along which the data flows. Every stream has a source and a destination. We can build a complex file processing sequence using a
series of simple stream operations. Two fundamental types of streams are Writing streams and Reading streams. While writing streams writes data into a file,
reading streams reads data from a file.
Types of Streams
The java.io package contains a large number of stream classes that provide capabilities for processing all types of data. These classes may be categorized into
two groups based on the data type on which they operate.
Byte stream classes
Character stream classes
Byte stream classes have been designed to provide functional features for creating and manipulating streams and files for reading and writing bytes.
Java Byte streams are used to perform input and output of 8-bit bytes. Java provides two kinds of byte stream classes:
Below are the subclasses of Input stream and Output stream classes:
FilterInputStream: An instance of this class contains some other input stream as a basic source of data for further manipulation.
FileOutputStream: An instance of this class is used to output a stream for writing data to a file or to a file descriptor.
ByteArrayInputStream: An instance of this class contains an internal buffer to read bytes stream.
ByteArrayOutputStream: An instance of this class contains an internal buffer to write a bytes stream.
ObjectInputStream: An instance of this class is used to deserialize an object after it has been serialized by ObjectOutputSteam.
ObjectOutputStream: An instance of this class is used to serialize an object which can be deserialized with ObjectInputStream.
29
SequenceInputStream: An instance of this class represents a logical concatenation of two or more input streams which are read in sequence, one after
Page
another.
PipedInputStream: An instance of this class provides a pipe or buffer for an input byte that works in the FIFO manner.
PipedOutputStream: An instance of this class provides a pipe or buffer for output byte that works in the FIFO manner.
FilterInputStream: An instance of this class contains some other input stream as a basic source of data for further manipulation.
o BufferedInputStream: This enables a FilterInputStream instance to make use of a buffer for input data.
o DataInputStream: An instance of this class enables reading primitive Java types from an underlying input stream in a machine-independent manner.
FilterOutputStream: An instance of this class contains some other output stream as a basic source of data for further manipulation.
o BufferedOutputStream: This enables a FilterOutputStream instance to make use of a buffer for output data.
o DataOutputStream: An instance of this class enables writing primitive Java types to an underlying output stream in a machine-independent manner.
Character streams can be used to read and write 16-bit Unicode characters. Java Character streams are used to perform input and output for 16-bit
Unicode. Like byte streams, there are two kinds of character stream classes:
Below are the subclasses of Reader stream and Writer stream classes:
BufferedReader: Provides an in-between buffer for efficiency while reading text from character input stream.
BufferedWriter: Provides an in-between buffer for efficiency while writing text to a character output stream.
InputStreamReader: An instance of this class provides a bridge from byte streams to character streams. Bytes are decoded into characters using a specified
character set.
o FileReader: An instance of this class is used for reading character files.
OutputStreamWriter: An instance of this class provides a bridge between character streams and byte streams. Characters are encoded into bytes using a
specified character set.
o FileWriter: An instance of this class is used for writing character files.
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally{
if (in != null) {
in.close();
}
30
if (out != null) {
out.close();
Page
}}}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
After compiling the above program and execute it, will result in creating output.txt file with the same content as we have in input.txt.
Java Random Access File provides the facility to read and write data to a file. Random Access File works with file as large array of bytes stored in the file system
and a cursor using which we can move the file pointer position.
A Random Access File can be created in four different access modes. The access mode value is a string. They are listed as follows:
Eg:
3.What are the features of AWT? Explain Container class and Frame window. How frame is created and information placed in it? Illustrate with the help of a
simple AWT program.
AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.
Java AWT components are platform dependent i.e. components are displayed according to the view of operating system.
AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
Data transfer classes, for cut-and-paste through the native platform clipboard
Page
Java AWT Hierarchy
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.
Creating a Frame
There are two ways to create a Frame. They are,
import java.awt.*;
public class Testawt
{
Testawt()
{
Frame f=new Frame(); //Creating a frame
Label l1 = new Label("welcome to java"); //Creating a label
f.add(l1); //adding label to the frame
f.setSize(300, 300); //setting frame size.
f.setVisible(true); //set frame visibility true
}
public static void main(String args[])
{
32
}
Creating Frame window by extending Frame class
import java.awt.*;
import java.awt.event.*;
4.Explain event handling in AWT programming with an example (Delegation Event Model).
Event
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has the code which is known as
event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism
to generate and handle the events.
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler.
Listener - It is also known as event handler. Listener is responsible for generating response to an event. From java implementation point of view the listener is
also an object. Listener waits until it receives an event. Once the event is received, the listener processes the event and then returns.
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
33
//create components
Page
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
5.What is Applet Class? Explain Applet life cycle. What is the use of Graphics class in Java? How parameters are passed to Applet?
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
o Plugin is required at client browser to execute applet. It manages the lifecycle of an Applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass of Component.
1. Applet is initialized.
2. Applet is started.
34
3. Applet is painted.
4. Applet is stopped.
Page
5. Applet is destroyed.
Lifecycle methods for Applet
The java.applet.Applet class have four life cycle methods and java.awt.Component class provides one life cycle methods for an applet.
java.applet.Applet class
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
import java.applet.Applet;
import java.awt.*;
myapplet.html
<html>
<body>
35
</body>
</html>
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
import java.applet.Applet;
import java.awt.Graphics;
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
36
Page
MODULE V
1.Explain JDBC architecture.
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the database.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC Architecture consists of two layers −
JDBC API: This provides the application-to-JDBC Manager connection. It uses a driver manager and database-specific drivers to provide transparent connectivity
to heterogeneous databases.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection. It ensures that the correct driver is used to access each data source. The driver manager
is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.
o DriverManager: This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver
using communication sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
37
o Driver: This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects.
Page
o Connection: This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication
with database is through connection object only.
o Statement: You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.
o ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you
to move through its data.
o SQLException: This class handles any errors that occur in a database application.
JDBC Drivers
Statement
Prepared Statement
Callable statement
Statement
The Statement interface represents the static SQL statement. It helps you to create a general purpose SQL statements using Java.
The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the
database.
Example :
Statement stmt=con.createStatement();
Once you have created the statement object you can execute it using one of the following methods.
execute(): This method is used to execute SQL DDL statements, it returns a boolean value specifying whether the ResultSet object can be retrieved.
executeUpdate(): This method is used to execute statements such as insert, update, delete. It returns an integer value representing the number of rows
affected.
executeQuery(): This method is used to execute statements that returns tabular data (example SELECT statement). It returns an object of the class
ResultSet.
Prepared Statement
The PreparedStatement interface extends the Statement interface. It represents a precompiled SQL statement which can be executed multiple times. This
accepts parameterized SQL quires and you can pass 0 or more parameters to this query.
You can create an object of the PreparedStatement (interface) using the prepareStatement() method of the Connection interface. This method accepts a query
(parameterized) and returns a PreparedStatement object.
Example :
PreparedStatement pstmt = con.prepareStatement(query);
Once you have created the PreparedStatement object you can execute it using one of the following methods.
execute(): This method executes normal static SQL statements in the current prepared statement object and returns a boolean value.
executeQuery(): This method executes the current prepared statement and returns a ResultSet object.
executeUpdate(): This method executes SQL DML statements such as insert update or delete in the current Prepared statement. It returns an integer value
representing the number of rows affected.
38
Callable Statement
Page
Example :
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");
Once you have created the CallableStatement object you can execute it using execute() method.
There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.
Example :
Here, Java program is loading mysql driver to establish database connection.
Class.forName("com.mysql.jdbc.Driver");
The getConnection() method of DriverManager class is used to establish connection with the database.
Example :
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","password") // “url”,”username”,”password”
The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the
database.
Example :
Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to
get all the records of a table.
Example :
ResultSet rs=stmt.executeQuery("select * from studdetails");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.
Example :
con.close();
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","password");
Statement stmt=con.createStatement();
String sql="INSERT INTO studdet VALUES ('Sarah',100)";
stmt.executeUpdate(sql);
System.out.println("inserted records into the table...");
ResultSet rs=stmt.executeQuery("SELECT * FROM studdet");
while(rs.next())
{
String name=rs.getString(1);
int rollno=rs.getInt(2);
System.out.println("Name:"+name);
System.out.println("Roll no:"+rollno);
}
}
catch(Exception e)
{
System.out.println("Exception"+e);
}
}
}
O/P:
inserted records into the table...
Name:Sarah
Roll no:100
IN Database,
4.What is Socket programming in Java? Write a program for Client-Server communication using socket.
Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client
to make a connection request. Java Socket programming is used for communication between the applications running on different JRE.
In one-way client and server communication, client sends a message to the server, server reads the message and prints it. Here, two classes are being used:
Socket and ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read and write message. The ServerSocket class
is used at server-side. The accept() method of ServerSocket class blocks the console until the client is connected. After the successful connection of client, it
returns the instance of Socket at server-side.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket.
public InputStream getInputStream() returns the InputStream attached with this socket.
public OutputStream getOutputStream() returns the OutputStream attached with this socket.
public synchronized void close() closes this socket
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients.
public Socket accept() returns the socket and establish a connection between server and client.
Page
Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here, we are using 8080 port number for the communication between the
client and server. You may also choose any other port number. The accept() method waits for the client. If clients connects with the given port number, it
returns an instance of Socket.
Eg:
ServerSocket ss=new ServerSocket(8080);
Socket s=ss.accept(); //establishes connection and waits for the client
Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need to pass the IP address or hostname of the Server and a port
number. Here, we are using "localhost" because our server is running on same system.
Example of socket programming where client sends a text and server receives and prints it.
Server application
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(8080);
Socket s=ss.accept(); //establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close(); //connection closed
}
catch(Exception e){
System.out.println(e);
} }
}
Client application
import java.io.*;
import java.net.*;
public class MyClient {
41
5.Explain the following terms: i) InetAddress ii) URL Connection iii) Datagram.
i) InetAddress
Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name for example www.google.com.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP address with its corresponding host name.
Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name resolutions.
Example:
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.google.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e){
System.out.println(e);
} }
}
Output:
Host Name: www.google.com
IP Address: 201.23.11.66
The Java URL class represents a URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web.
For example: https://www.google.com:80/images
Example:
import java.net.*;
public class URLDemo{
public static void main(String[] args){
42
try{
URL url=new URL("http://www.google.com:80/images");
System.out.println("Protocol: "+url.getProtocol());
Page
Output:
Protocol: http
Host Name: www.google.com
Port Number: 80
File Name: /images
iii) Datagram
A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.
Java DatagramPacket class represents a message that can be sent or received. If you send multiple packet, it may arrive in any order. Additionally, packet
delivery is not guaranteed.
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
ds.send(dp);
ds.close();
}
}
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
43
Page