0% found this document useful (0 votes)
9 views36 pages

WebTechnology.Unit.I.Notes

WebTechnology.Unit.I.Notes

Uploaded by

Ashad Muneer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views36 pages

WebTechnology.Unit.I.Notes

WebTechnology.Unit.I.Notes

Uploaded by

Ashad Muneer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Syllabus for ST 1

Unit 1

Introduction: Introduction and Web Development Strategies, History of Web and Internet, Protocols
Governing Web, Writing Web Projects, Connecting to Internet, Introduction to Internet services and
tools, Introduction to client-server computing. Core Java: Introduction, Operator, Data type,
Variable, Arrays, Methods & Classes, Inheritance, Package and Interface, Exception Handling, String
handling

Unit II

Web Page Designing: HTML: List, Table, Images, forms, CSS

Introduction to Web

● The Web is the common name for the World Wide Web, a subset of the Internet consisting
of the pages that can be accessed by a Web browser.
● Many people assume that the Web is the same as the Internet, and use these terms
interchangeably.
● However, the term Internet actually refers to the global network of servers that makes the
information sharing that happens over the Web possible.
● So, although the Web does make up a large portion of the Internet, but they are not one and
same.
What is World Wide Web (WWW)?

• It is a collection of Millions of files stored on thousands of computers (Web Servers) all over
the world.
• These files may be HTML Documents, Text Documents, pictures, videos, sounds, programs
etc.
• Created by Tim Berners Lee in 1991.

How Web Works?


The client sends are request to the server using Internet. The server sends the response back to the
client. The server can also interact with some database management system to manage the data.

History of the Internet

• Internet was developed by ARPANet in 1969.


• ARPANet stands for American Research Project Agency Network

Governing body of the Internet

● There is no central governing body of the Internet. Instead, each constituent network setting
follows its own lead and enforces its own policies.
● But even though no sole entity runs the Internet, there are still a few smaller institutions
that have a bit of control.

Organizations Governing the Internet

● Internet Governance Forum (IGF)

● Internet Architecture Board (IAB)

● Internet Corporation for Assigned Names and Numbers (ICANN)

● Internet Engineering Task Force (IETF)

● Internet Research Task Force (IRTF)

● World Wide Web Consortium (W3C)


Protocols Governing Web

● HTTP (Hyper Text Transfer Protocol)


● HTTPS (Hyper Text Transfer Protocol Secure)
● SMTP (Simple Mail Transfer Protocol)
● POP3 (Post Office Protocol version 3)
● MIME (Multipurpose Internet Mail Extensions)
● IMAP (Internet Messaging Access Protocol)
● FTP (File Transfer Protocol)
● TELNET (Terminal Networking)

HTTP (Hyper Text Transfer Protocol)

• HTTP is a pull protocol, the user pulls information from a remote site.
• Protocol consists of GET and POST commands to transfer data.
• HTTP uses cached files to speed up transfers
• HTTP Uses LAN accessible cache that is Proxy Server.
• Proxy allows for reduced load on the internet connection
HTTPS (Hyper Text Transfer Protocol Secure)
Hypertext Transfer Protocol Secure (HTTPS) is an extension of the Hypertext Transfer Protocol (HTTP).
It is used for secure communication over a computer network, and is widely used on the Internet. In
HTTPS, the communication protocol is encrypted using Transport Layer Security (TLS) or, formerly,
Secure Sockets Layer (SSL). The protocol is therefore also referred to as HTTP over TLS or HTTP over
SSL.

SMTP (Simple Mail Transfer Protocol)

• The protocol is very simple.


• SMTP is a push protocol; information is pushed to a remote site.
• It uses port 25.
• All files are ASCII text.

POP3 (Post Office Protocol version 3)

• It is mail access client.


• It uses port 110.
• Messages are downloaded to client but can be stored on server.
• Does not easily allow multiple clients.

IMAP (Internet Message Access Protocol)

• It is improved version of POP3


• Automatically assigns folders
• Leaves mail on server
• Only transfers as much as needed per message (headers, subject only on list)
• It uses port number 143

MIME (Multipurpose Internet Mail Extensions)

• Generally it is used for encoding.


• Handles Non-ASCII data in an ASCII transfer medium.
• Defines extensions to support binary attachments of arbitrary format
– Images, Audio, Video and multi-media messages
– Text having unlimited line length or overall length
– Multiple objects in a single message
– Character sets other than ASCII
– Multi-font messages

FTP (File Transfer Protocol)

• Used to Transfer files between two computers.


• It uses port 21
• Goals of FTP Service
– Promote sharing of files (programs and/or data)
– Encourage indirect/implicit use of remote computers
– Shield users from variations in file storage among hosts
– Transfer data reliably and efficiently

TELNET (Terminal Networking)

• It is also known as Network Virtual Terminal.


• TELNET is a protocol that provides bi-directional communications using Command Line
interface

Web Development Life Cycle

 Information Gathering
 Planning
 Design
 Development
 Testing
 Delivery or Hosting
 Maintenance Phase

What is web browser?


• Web browser is software application.
• It has ability to retrieving, presenting and traversing information resources on the World
Wide Web.
• First web browser is Nexus.
• National Center for Supercomputing Applications (NCSA) develop Netscape Navigator in
1994.
• In 1995 IE (Internet Explorer) is developed by Microsoft.

What is Web Applications?

• Web Application is any software which runs on web browser.


• It is created in a browser-supported programming language.
• It is based on Client-Server model

What is Web Team?


• Group of peoples which works together to develop web applications.
• Roles & Responsibilities of the team Members defined clearly.
• There should be no communication barrier between team members.
• Size of team may be varying organization to organization.
Introduction to client-server computing

Client–server model is a distributed application structure that partitions tasks or workloads between
the providers of a resource or service, called servers, and service requesters, called clients. Often
clients and servers communicate over a computer network on separate hardware, but both client and
server may reside in the same system. A server host runs one or more server programs, which share
their resources with clients. A client usually does not share any of its resources, but it requests content
or service from a server. Clients, therefore, initiate communication sessions with servers, which await
incoming requests. Examples of computer applications that use the client–server model are email,
network printing, and the World Wide Web.

The "client-server" characteristic describes the relationship of cooperating programs in an application.


The server component provides a function or service to one or many clients, which initiate requests
for such services. Servers are classified by the services they provide. For example, a web server serves
web pages and a file server serves computer files. A shared resource may be any of the server
computer's software and electronic components, from programs and data to processors and storage
devices. The sharing of resources of a server constitutes a service.

Introduction to Java
 Java is a high level class based object oriented programming language
 It is a general purpose programming language intended to let application developers Write
Once Run Anywhere (WORA)
 Java was originally developed by James Gosling at Sun Microsystems and released in 1995 as
a core component of Sun Microsystems' Java platform Sun Microsystems was acquired by
Oracle in 2010

History of Java

 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991
 The language was initially called Oak after an oak tree that stood outside Gosling's office
 Later the project went by the name Green and was finally renamed Java from Java coffee, a
type of coffee from Indonesia
 Sun Microsystems released the first public implementation as Java 1 0 in 1996
 The latest version is Java 17 released in September 2021

Different technologies in Java


 Java SE (Standard Edition)
 JAVA EE (Enterprise Edition)
 Java ME (Micro Edition)

Tools Required for Java Development


 Java Development Kit (JDK)
 Java Runtime Environment (JRE)
 Java IDEs (Eclipse, NetBeans, IntelliJ etc.)

Resource URL:
https://java.sun.com/

Java SE 17 Download
IntelliJ IDEA Community Edition Download

Writing First Java Program

public class Welcome{


public static void main(String[] args){
System.out.println("Welcome to Java");
}
}

Save the program with .java extension e.g. Welcome.java


What is class?

 A user defined data type used to classify different entities like Student, Employee, Book,
Department
 A class contains a set of data members and the methods applicable on an entity
 Classes can be of two types
o Library Classes
o User Defined Classes

What are library classes?

 The classes which are provided with Java Development Kit for Rapid Application Development
(RAD)
o String class
o Character class
o Math class
o System class
 String class provides the methods applicable on a string like length(), toUpperCase (),
toLowerCase ()
 Math class provides the methods required for mathematical operations like pow(), sqrt (),
log()
 System class provides reference variables and the methods to interact with the computer
system

Understanding System class

 The System class provides three built in reference variables to refer the input and output
devices in a computer system
o in refers to standard input (keyboard)
o out refers to standard output (monitor)
o err refers to standard error (monitor)
 These reference variables can be used to call the methods provided in their classes
InputStream and OutputStream

Methods applied on out and err reference variables

 print()
o To print some output to the monitor
 println()
o To print some output to the monitor with line break
 printf()
o To print formatted output to the monitor using format specifiers
What is entry point?

 Special method inside a class from where the runtime environment starts execution is called
as entry point
 Entry point can by any of three choices
o public static void main(String[] args)
o public static void main(String args[])
o public static void main(String... args)

Syntactical Rules of Java


 All keyword in lower case
 Class names starts with capital letter. Any new word get introduced, make its first letter as
capital. Such syntax is also known as Pascal Case
o String class
o BufferedReader class
o InputStreamReader class
 Method names start with small letters. Any new word get added make its first letter as capital.
o length()
o toUpperCase()

Compiling a Java Program


 Once the program it ready we can compile the program code using a Java IDE or on the
Console
 If compiling on the console we need the Java Compiler JAVAC.EXE provided with JDK
Syntax
JAVAC < programname
Example
JAVAC Welcome.java

What happens during compilation?


 During the compilation process, Java code get converted to another programming language
called as Byte Code language and stored as .class file

JAVAC Welcome.java  Welcome.class

 Here Welcome.class file is not in binary format but in Byte Code Format. We can de compile
the Welcome.class file to convert it back to .java file

How to run a class?


 If using a Java IDE, then simply use a context menu to compile and run the code
 If using Console then use Java Runtime Environment (JRE) JAVA.EXE provided with JDK

JAVA Welcome
Checking for version of JDK installed in your machine
 While compiling and running the Java programs we need two softwares
o JAVAC.EXE Java Compiler
o JAVA.EXE Java Runtime

 Both of these software must be of same version


 Check the versions using following statements
JAVA --version
JAVAC --version

File Naming Rules in Java

o A Java program file can have one or more classes


o The class can have any name and file can also have any name of choice
o But, if a class is declared as public using public keyword with it, then the program name can
class name must be same
o A Java Program can have many classes but only one public class

Primitive Data Types in Java


 Integer
o byte 1 byte
o short 2 bytes
o int 4 bytes
o long 8 bytes
 Floating
o float 4 bytes
o double 8 bytes
 Character
o char 2 bytes
 Boolean
o boolean undefined

Literals or Constant values


 The values that assign to some variable or used in some expression are called as literals or
constant values
 Can be of five types
o Integer Literals
o Float Literals
o Character Literals
o Boolean Literals
o String Literals
Integer Literal
 All numbers without decimal point are called integer literals
 Such values are of int type by default
 Use l or L suffix for long type values
Example
long num =12345L;

Types of Integer Literals


 Integer Literals can be of four types
o Decimal
o Octal
o Hexa Decimal
o Binary
 Decimal numbers can have 10 digits (0 to 9). It is default
 Octal numbers can have 8 digits (0 to 7). Starts with 0
 Hexa Decimal numbers can have 16 digits(0 to 9, A F). Starts with 0x or 0X
 Binary numbers can have two digits (0 or 1). Starts with 0b or 0B

Examples of Integer Literals


o int a=1234; //decimal
o int b=01234; //octal
o int c=0X1234; hexa decimal
o int d=0B01101; 0B01101;// binary

Note: If we print these values using print(), println () or printf () methods then its output will printed
as decimal number system
Floating Literals
 Such numbers are of double by default
 Use f or F as suffix with float type values
Examples
double x=123.55;
float y=123.55; //error
float =123.55F; //correct

Character Literals
 Characters are enclosed in single quotes
char ch =='A';
 Each character has corresponding ASCII value
char ch =65;
 Characters from different languages have their Unicode values
char z=' \u0910';

String Literals
 Enclosed in double quotes
 Managed by String class
Example
String str ="Hello";

Boolean Literals
 Can have true or false only
Examples
boolean married=false;
boolean rented=true;
Introduction to Packages

 Special folders which contains related set of classes are called as packages

Examples
o java.lang package
 Contains all commonly used classes String, Math, System, Integer, Character
etc.
 It is default Package
o java.util package
 Contains the collections and utility classes
 LinkedList , Stack, Queue, Scanner, Date
o java.io package
 Contains file and memory management related clsses
 BufferedReader, InputStreamReader, File, FileReader , FileWriter etc.

Importing classes from a package

 Before using a class from a package we need to import that class


 We can import single class or all the classes provided in the package using import command

Examples
import java.util.*;
import java.util.LinkedList;
import java.util.Scanner;

Terminologies in Java

 Class
 Instance
 Reference
 Constructor

What is class?
 A set of specifications or blueprint about an entity describing all possible data members and
the methods to be applicable on that entity
 Classes can be of two types
o User Defined classes
o Library classes
 Use class keyword to create a class user defined class

What is instance?
 A real entity created based on class specifications is called as instance
 To create an instance, we require two things
o new keyword
o Constructor
 An instance can be used to use the data members and the methods of that class

What is constructor?

 Special method inside a class having special features


o Same name as class name
o No return type
o Used to initialize data in data members
Example
o String class
 String() constructor
o Scanner class
 Scanner() constructor

Example of instance of String class

What is reference?
 Special variable which hold reference of an instance present somewhere in memory
 It can be used to use the properties and methods of the class it is referring

Example
String s=new String("Hello");

 Here s is called as reference or reference variable.


Getting Data Input from user

Method 1: Using Scanner class

 Allows to read any type of data using pre-defined methods


o String next() -- string without space
o String nextLine() -- string with space
o int nextInt()
o float nextFloat()
o double nextDouble()
 To use these methods we need instance of Scanner class

Scanner sc=new Scanner(System.in);

Example

Write a program (ScannerTest.java) to input data of a student rollno (int), name (string), gender
(char) and fees (float). Show that data.

Hint: To input a character you can first input the data as string using next() method and then fetch its
first character using charAt() method of String class

import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Roll No : ");
int rollno=sc.nextInt();
System.out.print("Name : ");
String name=sc.next();
System.out.print("Gender : ");
char gender=sc.next().charAt(0);
System.out.print("Fees : ");
float fees=sc.nextFloat();
System.out.printf("Roll No is %d, Name is %s, Gender is %c, Fees is
%f",rollno,name,gender,fees);
}
}

Note: When you try to input a string with space using nextLine() method, it may not work in
between. To handle such situations, you can use another method.

Method 2: Using BufferedReader class

When we press a key from keyboard (System.in), a stream of bits get produced (A  01000001)

Java provides InputStreamReader class to read this stream of bits and convert into readable format

These characters are passed to an instance of another class BufferedReader

To read the data from buffer using readLine() method of BufferedReader class

String readLine() throws IOException

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.*;
public class DataInputTest {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Scanner sc=new Scanner(System.in);
System.out.print("Roll No : ");
int rollno=sc.nextInt();
System.out.print("Name : ");
String name=br.readLine();
System.out.print("Gender : ");
char gender=sc.next().charAt(0);
System.out.print("Fees : ");
float fees=sc.nextFloat();
System.out.printf("%s %d %c %f",name,rollno,gender,fees);
}
}

What is an array?
Special variable which allows to store multiple values of same data type in continues locations. Each
value or item get placed at some index number. Index number starts with 0.

Arrays in Java are treated as objects and created using new keyword.
Arrays provide length property to get size of array.

Arrays can be created using any of three syntaxes

Syntax 1: Arrays with sample values


datatype []arrayname={value1, value2, value3, …};

Example
int []num={6,1,2,9,12};

Test Case
Write a program having an array with sample values. Show sum of the values in the array.
public class SumArray {
public static void main(String[] args) {
int []num={5,1,8,9,12};
int sum=0;
for(int i=0;i<num.length;i++)
sum=sum+num[i];
System.out.println("Sum is "+sum);
}
}

Using foreach loop

Java provides a variant of for loop called as foreach loop where you can work on an array without
knowing length of it and without using array indexing.

Syntax
for(datatype variable: arrayname){
statements;
}

Test Case
Write a program (SumArray.java) having an array with sample values. Show sum of the values in the
array using foreach loop
public class SumArray {
public static void main(String[] args) {
int []num={5,1,8,9,12};
int sum=0;
for(int n:num)
sum=sum+n;
System.out.println("Sum is "+sum);
}
}

Syntax 2: Creating an array of defined size

datatype []arrayname=new datatype[size];

Example
int []num=new int[10]; //array of 10 integers
Test Case
Write a program (BigSmall.java) to create an array to store 10 integer values. Input 10 integer values
and show the smallest and biggest of given values.

import java.util.Scanner;
public class BigSmall {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int []ar=new int[10];
for(int i=0;i<ar.length;i++)
ar[i]=sc.nextInt();
int min,max;
min=max=ar[0];
for(int i=1;i<ar.length;i++){
if(ar[i]>max) max=ar[i];
if(ar[i]<min) min=ar[i];
}
System.out.printf("Smallest is %d and Biggest is %d",min,max);
}
}

Syntax 3: Arrays with user defined size

datatype []arrayname=new datatype[variable];

Test Case
Write a program (BigSmall.java) to ask the user how many numbers to be input. Input that much of
integer type of values. Show the smallest and biggest of given values.

import java.util.Scanner;
public class BigSmall {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("How many numbers to input : ");
int num=sc.nextInt();
int []ar=new int[num];
System.out.printf("Enter %d integer values : ",num);
for(int i=0;i<ar.length;i++)
ar[i]=sc.nextInt();
int min,max;
min=max=ar[0];
for(int i=1;i<ar.length;i++){
if(ar[i]>max) max=ar[i];
if(ar[i]<min) min=ar[i];
}
System.out.printf("Smallest is %d and Biggest is %d",min,max);
}
}

Types of Array
Java provides two types of arrays
 One Dimensional Array
 Array of Array or Jagged Array
When an array can have only one row, it is called one dimensional array. All above examples
Are of one dimensional array.

When an array contains an array which refers to another array, it is called as array of array or Jagged
array. Such arrays allow to manage different number of columns in each row.

Syntax 1: Array of Array having different columns in each row


datatype [][]arrayname=new datatype[rows][];
arrayname[index]=new datatype[size];

Example
Declare an array having 4 columns in first row, 5 columns in second row and 6 columns in third row.

int [][]ar=new int[3][];


ar[0]=new int[4];
ar[1]=new int[5];
ar[2]=new int[6];

Syntax 2: Array of Array having equal number of columns in each row


datatype [][]arrayname=new datatype[rows][columns in each row];

Example
Declare an array of 3x4.
int [][]ar=new int[3][4];

Test Case
Write a program (ArrayOfArray.java) to create an array having 4 columns in first row, 5 columns in
second row and 6 columns in third row. Input that much of integer values and show of values in each
row.

import java.util.Scanner;
public class ArrayOfArray {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int [][]ar=new int[3][];
ar[0]=new int[4];
ar[1]=new int[5];
ar[2]=new int[6];

System.out.println("Enter 15 integers : ");


for(int i=0;i<ar.length;i++){
for(int j=0;j<ar[i].length;j++)
ar[i][j]=sc.nextInt();
}
System.out.println("Array with row wise sum is ");
for(int i=0;i<ar.length;i++){
int sum=0;
for(int j=0;j<ar[i].length;j++) {
System.out.printf("%d\t",ar[i][j]);
sum = sum + ar[i][j];
}
System.out.printf("= %d\n",sum);
}
}
}

Test Case

Write a program (Matrix.java) having two arrays of 2x3 and 3x4. Input the integer type and show the
arrays in matrix format along with matrix multiplication.

import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int [][]ar1=new int[2][3];
int [][]ar2=new int[3][4];
int [][]ar3=new int[2][4];
int i,j,k;
System.out.println("Enter 6 items in first array : ");
for(i=0;i<ar1.length;i++){
for(j=0;j<ar1[i].length;j++){
ar1[i][j]=sc.nextInt();
}
}
System.out.println("Enter 12 items in second array : ");
for(j=0;j<ar2.length;j++){
for(k=0;k<ar2[j].length;k++){
ar2[j][k]=sc.nextInt();
}
}

for(i=0;i<ar1.length;i++){
for(k=0;k<ar3.length;k++){
for(j=0;j<ar2.length;j++){
ar3[i][k]+=ar1[i][j]*ar2[j][k];
}
}
}
System.out.println("First Matrix is");
for(i=0;i<ar1.length;i++){
for(j=0;j<ar1[i].length;j++){
System.out.printf("%d\t",ar1[i][j]);
}
System.out.println();
}
System.out.println("Second Matrix is");
for(j=0;j<ar2.length;j++){
for(k=0;k<ar2[i].length;k++){
System.out.printf("%d\t",ar2[j][k]);
}
System.out.println();
}
System.out.println("Matrix multiplication : ");
for(i=0;i<ar1.length;i++){
for(k=0;k<ar1[i].length;k++){
System.out.printf("%d\t",ar2[i][k]);
}
System.out.println();
}
}
}

Exception Handling in Java

What is Exception Handling?


● A system to send an error message in runtime from the place a runtime error has occurred to
the place a method get called using a set of special classes called as exceptions.
● Java provides thousands of such classes suffixed with Exception
○ IOExcepton
○ SQLException
○ ClassNotFoundException
○ RemoteException
○ InputMismatchException

Sample Code Generating an exception


● Write a program to input a number and show square of it
Hierarchy of Exception classes

 The java.lang.Throwable class act as the root for Java Exception Hierarchy
 A Throwable class defines two child classes
o Exception
o Error

 Exceptions are unexpected event that disturbs normal flow of the program. We can handle
such events.
 An error is non-recoverable. We cannot handle them.
Types of Java Exceptions
● There are mainly two types of exceptions:
○ Checked
○ Unchecked
● Error is generally considered third type of exception

Difference between Checked and Unchecked Exceptions

● Checked exceptions are checked at compile-time. The classes that directly inherit the
Throwable class except RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException, etc.
● Unchecked exceptions are not checked at compile-time, but they are checked at runtime. The
classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
● Error is irrecoverable but they are also unchecked kind of. Some example of errors are
OutOfMemoryError, VirtualMachineError, AssertionError etc.

How to handle such runtime errors?


 Java provides five keywords to handle the runtime errors
o try
o catch
o throw
o throws
o finally

 Use try-catch block to try some statements and trap the runtime error
 If we don’t know the kind of error may occur in the program code, use the parent classes
Throwable or Exception to handle all such exceptions
 Here we can give some generalized message when a runtime error occurs
Tracking for Exception Name for Specialized Messaging
● We can track the exception class name that notified us about a runtime error
● Throwable class provides some common methods for all the exceptions
○ void printStackTrace()
■ Prints the complete error information
○ String getMessage()
■ Returns the error message only

Using multiple catch blocks

● The program code may throw multiple kind of exceptions at different moments
● We can use multiple catch blocks to handle different types of exceptions
● Use Throwable class at the bottom to handle those exceptions that are not discovered yet

What is finally block?


● Special block used with try to always execute some code irrespective of an exception
● One try can have many catch blocks but only one finally block at the bottom
Syntax
try{
statements;
}catch(Exception ex){
statements;
}
finally{
statements
}

What is throw keyword?


● A keyword used to throw an instance of some exception kind of class when some runtime
error occurs in some method or constructor.
Syntax
throw <exception kind of instance>;

What is throws keyword?


● A keyword used to send an instance of some exception kind of class from one method to
another method
● Such feature is also known as exception propagation
Syntax
<return type> methodname() throws exceptionclass{
}

Test Case
● Create a class MyMath having a static method factorial() which takes a number as argument
and returns factorial of given number.
● If the value passed to factorial() method is in negative then throw an instance of Exception
class with a message “Sorry! Negative values not allowed”
● Create a class Demo with entry point. Input the data from user and show factorial of that
number.
● Handle the exceptions

Difference between throw and throws?


● The throw keyword is used to throw an instance of some exception kind of class while throws
carries that instance to next method till try-catch block is reached
String Handling in Java

What is String?
● An alphanumeric data is known a string. It can have alphabets, digits and special characters
● It can have zero or more characters
● Managed by java.lang.String class

Different ways of defining strings


● Strings can be defined using two ways
○ As Literal
○ As instance
Examples of Literals
String x=""; //blank string
String y="A"; // single character string
String z="Hello 123 $"; // Multiple character string
Example of instance
String name=new String("Rohit Kumar");

Methods of String class


● String class provides a variety of methods to work on strings
○ int length()
○ boolean equals(String s)
○ boolean equalsIgnoreCase(String s)
○ String toUpperCase()
○ String toLowerCase()
○ char charAt(int index)
○ int indexOf(String s) – Searches from start. Returns -1 if not found
○ int lastIndexOf(String s) – Searches from end. Returns -1 if not found
○ int compareTo(String s) – returns 0 if equal, >0 for greater or <0
○ String substring(int start) – returns string from start to end
○ String substring(int start, int end) – returns string having characters end-start from
start position
Test Case
● Write a program to input an email ID and verify it with following rules
○ Minimum length 3
○ Maximum length 20
○ Must have at least one dot (.)
○ Must have one and only one @

How to compare strings?

● If a string is managed as literal we can use equality operator (==) or equals() or compareTo()
methods
● If a string is managed as instance use equals() or compareTo() methods
How to do the password masking in Java?
Using readPassword() method Console class. Provided in Java 6 and above.
What is immutable strings?
● A string that do not allow to change its contents is called as immutable strings
● String class is used to manage immutable strings
● When adding two strings with addition operator (+) it waste one memory space every time
due to immutable nature of String class

What are mutable classes?

● Special classes which allows to change the data in same location are called as mutable classes
● Java provides two classes to manage mutable data
○ StringBuffer class (Java 1.0)
○ StringBuilder class (Java 5.0)
● Use append() method to append the data
● Use reverse() method to reverse a string
What is OOPs?

OOPs stands for Object Oriented Programming System.

It is a system independent of any programming language to a goal “Building better and scalable
project management” using a set of components called as pillars of OOPs

1. Encapsulation
2. Abstraction
3. Polymorphism
4. Inheritance

These core pillars require three other components

1. Class
2. Instance
3. Reference

What is class?

A set of specifications or blueprint about an entity describing all possible data members and the
methods to be applicable on that entity.

A class used to create multiple instances of same type.

Use class keyword to define a class

Syntax

class <entityname>{

// members
}

Types of members inside a class

1. Data Members
2. Methods

Types of methods inside a class

1. Special methods
a. Constructor
b. Finalizer
c. Setter
d. Getter
2. General methods

What is constructor?

 Special method having special features


o Same name as class name
o No return type
o Used to initialize data in data members of an instance

What is setter?

 Special methods prefixed with set


 Used to update the value in some data member of an instance

What is getter?

 Special methods prefixed with get


 Used to return the value in some data member of an instance

Java provides a built-in reference called this to refer the current instance

Example

Entity  Customer

Data Members  cid, name, mobile, balance

Special Methods  Constructor, setter for mobile, getter for data members

General methods  deposit(), withdraw()


public class Customer {
int cid;
String name,mobile;
double balance;

public Customer(int cid, String name, String mobile, double


balance) {
this.cid = cid;
this.name = name;
this.mobile = mobile;
this.balance = balance;
}

public void setMobile(String mobile) {


this.mobile = mobile;
}

public int getCid() {


return cid;
}

public String getName() {


return name;
}

public String getMobile() {


return mobile;
}

public double getBalance() {


return balance;
}
void deposit(double amount){
balance+=amount;
}
void withdraw(double amount){
balance-=amount;
}

Create another class PNB with entry point

Create instance of Customer class with sample data

public class PNB {


public static void main(String[] args) {
Customer c1=new Customer(123,"Harish
Verma","1122334455",5000);
System.out.println(c1.getName()+", "+c1.getBalance());
c1.deposit(6000);
System.out.println(c1.getName()+", "+c1.getBalance());
c1.withdraw(1200);
System.out.println(c1.getName()+", "+c1.getBalance());
}
}

You might also like