You are on page 1of 35

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING.

PRACTICAL FILE SUBMISSION


BRANCH: CSE
SUB NAME: INTRODUCTION TO JAVA
PROGRAMMING LANGUAGE
Submitted By: Submitted to:
Amlesh kumar Mr.Deepak Choudhary
Enroll no:16105113021 Assistant Professor
Roll no : 16306 CSE Department
MCE Motihari
INDEX
S.No Name of experiment Perform date Page No. sign
1. Introduction of java 16.07.18
2. WAP in Java to print Hello Java 17.07.18
3 WAP in Java to perform sum operation 28.07.18
on two given number 10 & 20
4 WAP in java to accept two numbers 07.08.18
from user and perform sum operation.
5 WAP in java to accept a number from 14.08.18
user and check whether it is even or
odd.
6 WAP in java to accept an alphabet in 21.08.18
Lower case and check whether it is
Vowel or Consonant.
7 WAP in java to accept an alphabet in 28.08.18
Lower case and check whether it is
Vowel or Consonant.(using switch)
8 WAP in java to accept two numbers 04.09.18
from user and then accept the choice of
operation (+ - * /) to be performed.
Performed operation according to
choice.
9 WAP to print 1 to 10 using while, 11.09.18
dowhile and for loop.
10 WAP in java to accept a number from 18.09.18
user and print its factorial.
11 WAP to print pyramid of star 25.09.18
12 WAP in java to create an integer array 23.10.18
of size 10, accept input in this array and
print them.
13 WAP to implement Exception Handling 30.10.18
14 WAP in java to implement class and 30.10.18
object.
15 WAP in java to implement Constructor 20.11.18
16 WAP in java to implement Inheritance. 20.11.18
17 Mini Project in Applet 22.11.18
Experiment 1:
Introduction of Java
Java can be classified/studied under 5 major categories: Desktop Technologies (J2SE JAVA 2
STANDARD EDITION)
Web Technologies (J2SE)
Distributed Technologies (J2SE)
Enterprise Technologies (J2EE)
Micro Technologies (J2ME)

Desktop Technologies
+ Core Java
+ Java 2

Scope: Desktop/LAN

Web Technologies
+ Servlets
+ Java Server Pages (JSP)
+ Java Server Faces (JSF)
Scope: Internet/Intranet/Extranet

Distributed Technologies
+ Remote Method Invocation (RMI)

Scope: Distributed storage/ Distributed Processing

Enterprise Technologies
+ Java 2 Enterprise Edition (J2EE)
+ Enterprise Java Bean (EJB)

Scope: Huge Database Applications

Micro Technologies
+ Java 2 Micro Edition (J2ME)

Scope: Mobile/Pagers/Set Top Boxes

More about Java


+ Java is a product from SUN Microsystems.
SUN - Stanford University Network

+ Java was introduced in the year 1991 (initially introduced by the name of OAK)
+ Popularity of Java is because of
1. Rich Constructs
2. Rich library
3. Applets Applets:
Small programs written in Java executed within Browser.
Example Yahoo! Chat Applet Servlets:
Small programs written in Java executed on Servers.
Midlets:
Small programs written in Java executed in Micro devices.
Example Mobile

Buzzwords/Characteristics/Features of Java:
1. Simple Program written in Java is Simple (Resembles with c/c++) 2.
Portable Program written in java is Platform independent.
3. Powerful program in Java are powerful due to its rich library
4. Secure and Robust
+ No Pointers
+ Does not interact with hardware directly.
5. True OOP Structure:
• Encapsulation: “Hiding of non-essential details”
• Data Binding
• Data Hiding
1. Security
2. To avoid Complexity

• Abstraction: “Give essential details in summarized form.”


• Inheritance: “Reusability, extending, and overriding.”
• Polymorphism : “Multiple Use”
6. Compiled and Interpreted, yet high performance:

Save Compile
C/C++ -------- .c/.cpp ----------- .obj

(Machine code)
Save Compile Interpret
Java --------- .java ----------- .class ------------ OUTPUT
javac java
(Byte Code)

+ Byte code is not the machine code it is similar to machine code.

+ Machine code = Binaries + Machine Dependencies

+ Byte code = Machine Code - Machine Dependencies

Requirement for Interpretation


+ JVM: Java Virtual Machine +
JRE: Java Run Environment
7. Platform independent:
Java program are platform independent but not JVM and JRE.

Software Requirements
Jdk (Java Development Kit) jdk 1.6
Compiler javac
Interpreter java
Debugger jdb
Documentation javadoc
To view Applets appletviewer
Java API (Application Programming Interface)

+ Editor (notepad, vi, Edit) Or


IDE (NetBeans, Eclipse, Kawa)

Syntax of java Program:


class <ClassName>
{
//Body
}
Sample Program:
class First
{ public static void main(String args[])
{
System.out.println(“Hello World”);
}
}

public: it can be called from anywhere


static: No object is required void: It does
not return any value main: Name of
function that gets executed
String args[]: Command line argument, args is a array of datatype String.
System.out.println(“message”); //New line after message
System.out.print(“message”);// no new line after message

\n \t \a \\ \” \’ are same as they were in c/c++.

// Single line comment


/* Multi line comment */

Steps to Set the Path of Java:

• + Start | Find | Files and Folder


• Look for “javac.exe “within My Computer
• In case Not found Install jdk 1.6
• If found Select javac.exe. | Right click | Properties
• copy the location Ex. C:\Program Files\Java\jdk1.6.0_11\bin
• My Computer| Properties| Advanced| Environment variable |System Variable Select
Path| Edit

Variable name: Path


Variable value: C:\Program Files\Java\jdk1.6.0_11\bin <paste it>

Step to write and execute (run) java program Using Notepad:


• Open notepad
Start | Run | Notepad or Program | Accessories | Notepad
2. Type program

3. Save it
+ Class name and file name should be same.
+ Extension should be .java.
+ It is case Sensitive.
• Suppose save the program in d:\data
• And class name is First
4. Compile it+ Go to Dos prompt.
- Start | Run | cmd (XP/NT/2000)

+ Go to the directory where you have saved.


C:\windows\desktop> D:
D :\> cd Data
D:\Data> javac First.java

Syntax:
javac FileName.java +
Execute it/interpret it
D:\Data>java First Syntax:
java First
Experiment 2: WAP in Java to print Hello Java

Syntax of java Program:


class <ClassName>
{
//Body
}
Steps:
Open notepad
Start | Run | Notepad or Program | Accessories | Notepad
2. Type programclass First
{ public static void main(String args[])
{
System.out.println(“Hello Java”);
}
}
3. Save it
+ Class name (First) and file name(First) should be same.
+ Extension should be .java.
+ It is case Sensitive.
• Suppose save the program in f:\java files
• And class name is First
4. Compile it
+ Go to Dos prompt.
- Start | Run | cmd (XP/NT/2000)

+ Go to the directory where you have saved.


C:\windows\desktop> F:
F:\> cd Data
F:\java files> javac First.java

Syntax:
javac FileName.java +
Execute it/interpret it
F:\java files>java First
Syntax:
java First

Output:
Experiment 3: WAP in Java to perform sum operation on two given number 10 &
20
Data types
+ Data types in any language specifies the type of data to be stored and the size of memory to be
allocated.
+ Data types can be classified in two category
1. Fundamental
2. Derived
Fundamental/Pre-Defined/Built-In/Primitive
“Data types that the compiler understands”
char 2 bytes 216-1
byte 1 byte 28-1
short 2 bytes 216-1
int 4 bytes 232-1
long 8 bytes 264-1
Java uses EDBIC (Extended Binary Code, Decimal Interchange Code).
C/C++ uses ASCII.
Variables
+ Variables are temporary memory location used to store a value.
+ Value stores in a variable can change /vary.
+ Variable naming conventions
- maximum variable name can have 255 characters
- no spaces, no special characters except underscore(_) and dollar($).
- Should start with an alphabet.
- Should be unique within its scope.
- Should not be a keyword.
+ Declaration
<DataType> <variableName>;
Ex. char c;
int num;
float f;

NOTE: Java makes use camel Notation for variable naming.


Ex. myVar, oneTwoThree
+ Initialization
num =10;
c = ‘A;’
+ Declaration & Initialization char
c = ‘A’;
int num =10;
10.5 //double
10.5f // float 10.5d
//double

** f & d are literals.


+ Literals are used to specify data type of a value.
Program:
class Addition
{
public static void main(String args[])
{ int
a,b,c;
a=10;
b=20;
c=a+b;
System.out.println("the sum is "+c);
}
} Output:

Notes:
‘+’ concatenation operator which is used to concatenate a message with a variable.

Experiment 4: WAP in java to accept two numbers from user and perform sum
operation.
Accept input from user:
• To take quick input from User “Scanner “class is used.
• This class comes from “java.util” package. Import scanner class import java.util.Scanner;
• Create the object of Scanner within main function
Scanner x=new Scanner(System.in);
Here x is the object of class Scanner
• To accept a string from user (with space)
String str;
str= x.nextLine();
• To accept a string from user (without space)
String str;
str= x.next();
• To accept a character value from user
char a;
a=x.next().charAt(0);
• To accept integer value from User
int a; a=x.nextInt();
• To accept float value from user
float a; a=x.nextFloat();
Program:
import java.util.Scanner;
class AdditionUser {
public static void main(String args[])
{
int a,b,c;
Scanner in=new Scanner(System.in);
System.out.println("enter a");
a=in.nextInt();
System.out.println("enter b");
b=in.nextInt(); c=a+b;
System.out.println("the sum is "+ c);

}
}

Output:

Experiment 5: WAP in java to accept a number from user and check whether it is
even or odd.

Conditional/decision/selection structures:
They are used to select one out of multiple options. Like C/C++ even java provides:
+ if
If: it can be used in 3 different ways.
Ways of using ‘if’
1. if(<cond>)
{
//true part
}

2. if(<cond>)
{
//true part
}
else
{
//false part
}

3. if(<cond>) //Complexsive/Multiple if
{
//true part
}
else if(<cond>)
{
//true part
}
else
{
//fal
se
part
}
Program:
import java.util.Scanner;
class Ifelse {
public static void main(String args[])
{
int a;
Scanner in=new Scanner(System.in);

System.out.println("enter a");
a=in.nextInt(); if(a%2==0)
{
System.out.println("a is even");
}
else
{
System.out.println("a is odd");
}
}
}

Output:

Experiment 6: WAP in java to accept an alphabet in Lower case and check whether
it is Vowel or Consonant.

Program:
import java.util.Scanner; class
TestVowelCon
{
public static void main(String args[])
{ char
ch;
Scanner in=new Scanner(System.in);
System.out.println("enter the apphabet");
ch=in.next().charAt(0);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
{
System.out.println("Vowel");
}
else
{
System.out.println("Consonent");
}
}
}

Output:
Experiment 7: WAP in java to accept an alphabet in Lower case and check whether
it is Vowel or Consonant.(using switch)

Switch:
switch(<variable>)
{
case <value1>://true-part
break;
case <value2>: //true-part break;
.
.
default: //false part
}

Program :

import java.util.Scanner;
class SwitchVowelCons
{
public static void main(String args[])
{ char
ch;
Scanner in=new Scanner(System.in);
System.out.println("enter the apphabet");
ch=in.next().charAt(0); switch(ch)
{ case 'a':case 'e':case 'i':case 'o':case 'u':case 'A':case 'E':case 'I':case 'O':case 'U':
{
System.out.println("vowel");
break; } default:
{
System.out.println("consonent");
}
}
}
}

Output:
Experiment 8: WAP in java to accept two numbers from user and then accept the
choice of operation (+ - * /) to be performed. Performed operation according to
choice.

import java.util.Scanner; class


Calculator
{
public static void main(String args[])
{ int
a,b,res;
char ch;
float div;
Scanner in=new Scanner(System.in);
System.out.println("enter the a");
a=in.nextInt();
System.out.println("enter the b");
b=in.nextInt();
System.out.println("enter the choice + - * /");
ch=in.next().charAt(0); switch(ch) { case '+': {
res=a+b;
System.out.println("the sum is " + res);
break; } case '-': { res=a-b;
System.out.println("the substraction is " + res);
break; } case '*': { res=a*b;
System.out.println("the multiplication is " + res);
break; } case '/': { div=(float)a/b;
System.out.println("the division is " + div);
break; } default:
{
System.out.println("wrong input");
}
}
}
}
Output:
Experiment 9: WAP to print 1 to 10 using while,do-while and for loop.

Iterations/Looping/Repetitive Structure
+ to repeat set of statements
+ Like C/C++, even java provides
- while
- do..while
- for

+ Parts of iteration structure


- initialization : starting value i= 1
- condition : ending value i<=10
- re-initialization : step value i++

+ while(<cond>)
{
//statements
//reinitialization
}

+ do
{
//statements
//re-initialization
}while(<cond>)

+ for(<initialization>;<cond>;<re-initialization>)
{
//statements
}

Program :(A)
import java.util.Scanner; class
WhileLoopTest
{
public static void main(String args[])
{
int i=1; while(i<=10)
{
System.out.println(i);
i++; }
}
}
Output:

Program :(B) import


java.util.Scanner; class
ForLoopTest
{
public static void main(String args[])
{
for(int i=1;i<=10;i++) {
System.out.println(i);
}
}
}
Output:

Program : (C) import


java.util.Scanner;
class DoWhileLoopTest
{
public static void main(String args[])
{ int
i=1;
do
{
System.out.println(i);
i++; }while(i<=10);
}
}
Output:
Experiment 10: WAP in java to accept a number from user and print its factorial.

Program:
import java.util.Scanner; class
FindFact
{
public static void main(String []dee)
{
Scanner x=new Scanner(System.in); int
a,f=1;
System.out.println("enter any number:");
a=x.nextInt(); for(int i=1;i<=a;i++) f=f*i;
System.out.println("factoial is "+f);
}
}

Output:
Experiment 11: WAP to print
*
**
***
****
***** Program:
class StarPrint {
public static void main(String []argas)
{ for(int i=1;i<=5;i++)
{ for(int j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.print("\n");
}
}
}
Output:
Experiment 12: WAP in java to create an integer array of size 10, accept input in
this array and print them.
Arrays
Collection of similar data types Terms:
+ Each data item in an array is called “element”.
+ The counting of elements is called “index” or “subscript”.
+ The total no. of elements is called “length” or “size”. +
Index always starts from 0.

Declaration & Initialization:

<Data Type> <arrayVariable>[] = new <Data Type>[size]

Eg. int num[] =new int[10];


float f[] = new float[5]

Declaration:
int[] num,a; int num[]; int []num; float[] f; float f[]; float []f;

Initialization: num =
new int[10];
f = new float[5];
Program:
import java.util.Scanner; class
ArrayTest
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int ar[]=new int[10];
System.out.println("enter element"); for(int
i=0;i<=9;i++)
{ ar[i]=in.nextInt();
}
System.out.println("the elements are");
for(int i=0;i<=9;i++)
{
System.out.println(ar[i]);
}
}
}
Output:

Experiment 13: WAP to implement Exception Handling Exception


Handling
Types of errors
• Compile Time/Syntax
E.g. Missing ;, misspelling, missing “, using variable without declaration.
• Runtime
E.g. Division by Zero, Invalid conversion accessing invalid index of an array.
1. Runtime error results in an exception.
2. Whenever Exception occurs Java creates an object of “Exception” or its Derive class.
3. Exception leads to abnormal termination of program giving some garbage on screen.
4. Handling means making the user aware with the problem.

Program:
class Exception1
{
public static void main(String args[])
{
int a = 10,b= 0,c;
c=a/b;
System.out.println("Result is : "+c);
}
}
Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero at Exception1.main


(Exception1.java:6)
For Exception Handling Java provides
+ Constructs (Collection of statements)
1. try
2. catch
3. finally

+ Statements
1. throw
2. throws
try
+ All statements that may result in an error are written within “try” block.
+ A method can contain nested or multiple “try” blocks
catch
+ Every “try” should be followed by at least one “catch” block.
+ Multiple catch works like “case” in “switch”, only one will be executed
depending on exception generated.
+ catch is conditional.
+ catch receives an argument exception or its derive class.

Experiment 14: WAP in java to implement class and object.


Class : Class is a collection of member data and member function.
Syntax of class:
<Access Specifier> class <ClassName>
{
//member Data
//Member functions
}
Access specifier specifies the scope of member data, member functions, classes and interfaces.
There are four access specifiers in java
+ Private: within class
+ Protected: within class & derive class
+ Package/default: within folder/directory +
Public: anywhere

Package is the default access specifier.


Syntax:
To create an object
<ClassName> <objectName> = new <ClassName>();

Each object created in java is created dynamically; hence, the keyword new is used.
<ClassName> <objectName>;
<objectName> = new <ClassName>(); Program:
import java.util.Scanner; class
ClassTest
{ private int x,y;
public void getdata()
{
Scanner in=new Scanner(System.in);
System.out.println("enter x");
x=in.nextInt();
System.out.println("enter y");
y=in.nextInt();
}
public void showdata()
{
System.out.println("x is "+ x);
System.out.println("y is "+ y);
}
void showsum()
{ int
z;
z=x+y;
System.out.println("the sum is "+ z);
}
public static void main(String args[])
{
ClassTest t=new ClassTest();
t.getdata();
t.showdata();
t.showsum();
}
}
Output:
Experiment 15: WAP in java to implement Constructor
Constructors
+ Constructors are used for initialization of user defined data types in various forms.
+ Constructors are special member functions:
1. same name as of a class
2. no return type, not even void
3. Implicitly called whenever an object is created.
4. Executed only once in the life span of a object.
Destructors:
+ There are no destructors in java provides a utility called Garbage collection, this utility
executes periodically & releases unused memory. + Whenever it executes it invokes
Program:
import java.util.Scanner; class
TestConst
{
private int a,b,c; public
TestConst()
{
Scanner in=new Scanner(System.in);
System.out.println("enter three number:");
a=in.nextInt(); b=in.nextInt();
c=in.nextInt(); }
public TestConst(int x)
{
a=x;
b=x;
c=x;
}
public TestConst(int p,int q,int r)
{ a=p; b=q; c=r; }
public void show()
{
System.out.println("First Number is "+ a);
System.out.println("Second Number is "+ b);
System.out.println("Third Number is "+ c);
}
public static void main(String []dee)
{
TestConst t=new TestConst();
TestConst t1=new TestConst(5);
TestConst t2=new TestConst(10,20,30);
t.show(); t1.show(); t2.show();
}
}

Output:
Experiment 16: WAP in java to implement Inheritance.

Inheritance
+ Passing properties from one class to another.
+ Properties include member data and member functions.
+ The class that gives the properties is called base/super/parent class.
+ The class that receives the properties is called derive/sub/child class
+ Reasons
- Reusability
- Extending
- Overriding
Types of inheritance
1. Single 2. Multiple
A A

B B C
3. Multilevel 4. Hybrid
A A
BBC

C D

5. Hierarchical

B C
D E
NOTE:
+ Java does not support multiple Inheritances. One child class can have one base class.
+ Java does not support virtual method, virtual class and virtual data.
+ Java does not support friend classes and friend functions.
+ Java does not support inline functions, operator overloading & templates.

To inherit a class in Java “extends” keyword is used.

Syntax:
class <DeriveClass> extends <BaseClass>
Program:
import java.util.Scanner; class
TestInheri
{ private int x;
protected int y;
public void getdata()
{
Scanner in=new Scanner(System.in);
System.out.println("enter x"); x=in.nextInt();
System.out.println("enter y"); y=in.nextInt();
}
public void showdata()
{
System.out.println("the x is " + x);
System.out.println("the y is " + y);
}
}
class TestInheri1 extends TestInheri
{ private int k;
public void getk() {
Scanner in=new Scanner(System.in);
System.out.println("enter k");
k=in.nextInt(); } public void showk()
{
System.out.println("the k is "+ k);
}
public void showsum()
{
System.out.println("the sum is "+ (y+k));
}
public static void main(String args[])
{
TestInheri1 t=new TestInheri1(); t.getdata();
t.showdata();
t.getk();
t.showk();
t.showsum();
}
}
Output:

Experiment 17 : Mini Project in Applet .

Program:
/*
NIGHT CLOCK */

import java.applet.Applet;

import java.util.*; import java.awt.*;


import java.text.SimpleDateFormat;

public class neight_watch extends Applet implements Runnable {


Thread t=null;
String time="" , date = "" , str = ""; public
void init()
{
setSize(new Dimension(600,200)); t=new
Thread(this);
t.start();
}

public void Time()


{
Date d = new Date();
SimpleDateFormat ft= new SimpleDateFormat("hh mm ss aa");
time=ft.format(d);
SimpleDateFormat fd=new SimpleDateFormat("E dd-MM-YYYY");
date=fd.format(d);
}
public void run()
{
try
{
while(true)
{
if(str.equals(" "))
{
str=" : : " ;

} else
{
str="";
}
Time();
repaint();
t.sleep(500);

}
}
catch(Exception e){}
}
public void paint(Graphics g)
{
setBackground(new Color(36,36,36));
Font ftime=new Font("Digital-7 mono",Font.PLAIN,100); g.setFont(ftime);
g.setColor(new Color(60,60,60));
g.drawString("00 00 00",50,100);
g.drawString(" : :",50,100);
g.setColor(new Color(0,162,232));
g.drawString(time,50,100);
g.drawString(str,50,100);
//date
Font fdate=new Font("Digital-7 mono",Font.PLAIN,40); g.setFont(fdate);
g.drawString(date,170,160);
}
}

Output: