DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB
(CS2107)
LABORATORY MANUAL & RECORD
B.Tech (CSE) (With effect from 2022-23 admitted batches)
(II YEAR- I SEM)
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE
(APPROVED BY AICTE, AFFILIATED TO ANDHRA UNIVERSITY,
ACCREDITED BY NAAC-A GRADE, ISO 9001:2015 CERFIFIED)
PM PALEM, VISAKHAPATNAM-41,
www.svpce.edu.in
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING
INSTITUTE VISION AND MISSION
VISION
To be a premier institute of knowledge of share quality research and development
technologies towards national buildings
MISSION
1. Develop the state of the art environment of high quality of learning
2. Collaborate with industries and academic towards training research innovation and
entrepreneurship
3. Create a platform of active participation co-curricular and extra-curricular activities
DEPARTMENT VISION AND MISSION
VISION
To impart quality education for producing highly talented globally recognizable technocrats
and entrepreneurs with innovative ideas in computer science and engineering to meet
industrial needs and societal expectations
MISSION
To impart high standard value-based technical education in all aspects of Computer
Science and Engineering through the state of the art infrastructure and innovative
approach.
To produce ethical, motivated, and skilled engineers through theoretical knowledge
and practical applications.
To impart the ability for tackling simple to complex problems individually as well
as in a team.
To develop globally competent engineers with strong foundations, capable of “out
of the box” thinking so as to adapt to the rapidly changing scenarios requiring
socially conscious green computing solutions.
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
Graduates of B. Tech in computer science and Engineering Programme shall be able to
PEO1: Strong foundation of knowledge and skills in the field of Computer Science and
Engineering.
PEO2: Provide solutions to challenging problems in their profession by applying computer
engineering theory and practices.
PEO3: Produce leadership and are effective in multidisciplinary environment.
PROGRAMME SPECIFIC OUTCOMES (PSOs)
PSO1: Ability to design and develop computer programs and understand the structure and
development methodologies of software systems.
PSO2: Ability to apply their skills in the field of networking, web design, cloud computing
and data analytics.
PSO3: Ability to understand the basic and advanced computing technologies towards getting
employed or to become an entrepreneur
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PROGRAM OUTCOMES
DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING
1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.
2. Problem Analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences and
engineering sciences.
3. Design/Development of Solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety and the cultural, societal and environmental considerations.
4. Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modernengineeringandITtoolsincludingpredictionand modellingto complexengineering activities with
an understanding of the limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7. Environment and Sustainability: Understand the impact ofthe professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of,and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
9. Individual and Team Work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, give and receive clear instructions.
11. Project Management and Finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12. Life-Long Learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
GENERAL LABORATORY INSTRUCTIONS
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with
the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if
any) needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students/Faculty must keep their mobile phones in SWITCHEDOFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if
anybody found loitering outside the lab / class without permission during working hours
will be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves
the lab after completing the task(experiment) in all aspects. He/she must ensure the system/
seat is kept properly
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Course Objectives:
1. Introduce the basic structure and syntax of Java programs.
2. To develop programs using basic OOPS concepts such as classes and objects.
3. To implement programs using Inheritance concepts.
4. To implement programs using Exception handling.
5. To design applets and GUIs with layout managers.
6. Multithreading, file I/O, networking, applet programming, and GUI layout management.
Course Outcomes (CO) :
• Ability to write and understand the basic structure of a Java program.
• Student will be able to use OOPs concepts.
• Ability to apply Inheritance concepts to several problems.
• Ability to use Exception Handling concepts.
• Skill in implementing inheritance and method overriding for code reuse and specialization.
• Modularize the application using packages
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CS2105 OBJECT ORIENTED PROGRAMMING THROUGH JAVA
SYLLABUS
Introduction to Java: Basics of Java programming, Data types, Variables, Operators,
Control structuresincludingselection,Looping,Java methods, Overloading,Math
class,Arraysinjava.
Objects and Classes: Basics of objects and classes in java, Constructors, Finalizer,
Visibility modifiers, Methods and objects, Inbuilt classes like String, Character, String
Buffer, File, this reference
Inheritance and Polymorphism:Inheritance in java, Super and sub class, Overriding,
Object class, Polymorphism, Dynamic binding, Generic programming, Casting objects,
Instance of operator, Abstract class, Interface in java, Package in java, UTIL package.
Event and GUI programming: Event handling in java, Event types, Mouse and
keyevents, GUI Basics, Panels, Frames, Layout Managers: Flow Layout, Border Layout,
Grid Layout, GUI components like Buttons, Check Boxes, Radio Buttons, Labels, Text
Fields, Text Areas, Combo Boxes, Lists, Scroll Bars, Sliders, Windows, Menus, Dialog
Box, Applet and its life cycle, Introduction to swing
I/O programming: Text and Binary I/O, Binary I/O classes, Object I/O, Random
Access Files.
Multithreading in java: Thread life cycle and methods, Runnable interface, Thread
synchronization, Exception handling with try-catch-finally, Collections in java, Introduction
to JavaBeans and Network Programming.
Java Database Connectivity (JDBC): JDBC Product, Types of Drivers, Two-Tier
Client/Server Model, Three-Tier Client/Server Model, Basic Steps of JDBC,
Creating and Executing SQL Statement, The ResultSet Object, Working with Database MetaData
Interface
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Reference Books:
1 IntroductiontoJavaProgramming(ComprehensiveVersion),DanielLiang,Seventh
Edition, Pearson.
2 ProgramminginJava,SachinMalhotra&SaurabhChaudhary,OxfordUniversity
Press.
3 Murach’sBeginningJava2,DougLowe,JoelMurachandAndreaSteelman,SPD.
4 CoreJavaVolume-IFundamentals,EightEdition,Horstmann&Cornell,Pearson
Education.
5 The CompleteReference,Java2 (FourthEdition),HerbertSchild,TMH.
6 JavaProgramming,D.S.Malik,CengageLearning.
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
TABLE OF CONTENTS
SI.No CONTENT Page No
1 Program to define a structure of a basic JAVA program 11
2 Program to define the data types, variable, operators, arrays and 12-19
control structures.
3 Program to define class and constructors. Demonstrate 20-21
constructors.
4 Program to define class, methods and objects. Demonstrate 22-24
method overloading.
5 Program to define inheritance and show method overriding 25-27
6 Program to demonstrate Packages. 28-30
7 Program to demonstrate Exception Handling. 31-35
8 Program to demonstrate Multithreading. 36-38
9 Program to demonstrate I/O operations. 39-44
10 Program to demonstrate Network Programming. 45-51
11 Program to demonstrate Applet structure and event handling. 52-54
12 Program to demonstrate Layout managers. 55-57
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
1. Program to define a structure of a basic java program
Public class MyJavaProgram
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
Output:
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
2. Program to define the data types, variable, operators, arrays and control
structures.
a) Datatype
public class DataTypesExample{
public static void main(String[] args){
int integerValue = 10;
double doubleValue=3.14;
char charValue = 'A';
boolean booleanValue = true;
String stringValue="Hello,Java!";
System.out.println("Integer:"+integerValue);
System.out.println("Double: " + doubleValue);
System.out.println("Char: " + charValue);
System.out.println("Boolean:"+booleanValue);
System.out.println("String: " + stringValue);
}
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 2
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
b) Variable and Operators:-
public class VariablesAndOperatorsExample{
public static void main(String[] args) {
int a = 5;
int b=2;
int sum = a+ b;
int difference=a-b;
int product = a * b;
int quotient = a / b;
int remainder=a%b;
System.out.println("Sum: " +sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
System.out.println("Remainder:"+remainder);
}
}
Output :
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 3
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
c) Arrays :-
public class ArraysExample{
public static void main(String[] args){
int[] intArray={1,2,3,4,5};
char[] charArray={'A','B','C','D', 'E'};
System.out.println("IntegerArray:");
for (int i :intArray)
{
System.out.println(i+" ");
System.out.println();
System.out.print("CharArray:");
for (char c :charArray) {
System.out.println(c+" ");
Output:
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 4
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
d) Control Structures:-
If –else :-
public class IfElseExample{
public static void main(String[] args){
int a = 5;
intb=2;
if(a>b){
System.out.println("aisgreaterthanb");
}else {
System.out.println("bisgreaterthana");
}}
Output:
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 5
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
While loop :-
public class WhileLoopExample{
public static void main(String[] args){
int i = 0;
while(i< 5) {
System.out.println("Valueofi:"+i);
i++;
}
Output:-
For–Loop:-
public class ForLoopExample{
public static void main(String[] args){
System.out.println("Values in the range[0,4]:");
for (int j = 0; j < 5; j++) {
System.out.println(j+" ");
}}}
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 6
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Output:-
Switch Statement:-
public class SwitchStatementExample
Public static void main(String[] args){
int a =2;
switch(a){
case 1:
System.out.println("a is 1");
break;
case 2:
System.out.println("ais2");
break;
default:
System.out.println("aisneither1nor2");
}}
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 7
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 8
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
3. Program to define class and constructors. Demonstrate constructors
public class Person {
private String name;
private int age;
public Person() {
this.name = "Unknown";
this.age=0;
}
public Person(String name, int age) {
this.name = name;
this.age=age;
}
void displayInfo() {
System.out.println("Name:"+name);
System.out.println("Age: " + age);
}
public static void main(String[] args)
{
Person person1 = new Person();
System.out.println("Person1:");
person1.displayInfo();
System.out.println();
person2 = new Person("John Doe",25);
System.out.println("Person 2:");
person2.displayInfo();
}
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 9
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Output:
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 10
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
4. Program to define class, methods and objects. Demonstrate method
over loading.
a) Methods:-
public class MathOperations
public int add(int a, int b)
{
return a+b;
}
int add(inta,intb,intc){
return a +b+c;
public double multiply(doublex,doubley)
return x * y;
}
public static void main(String[] args)
{
MathOperations mathOps=new MathOperations();
sum1 = mathOps.add(3, 5);
int sum2=mathOps.add(2,4,6);
double product=mathOps.multiply(2.5,3.0);
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 11
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
System.out.println("Sum (two integers): " + sum1);
System.out.println("Sum (three integers): " + sum2);
System.out.println("Product(twodoubles):"+product);}}
Output:-
b) Method Overloading:-
publicclassMethodOverloadingExample
publicstaticintadd(inta,intb)
{
return a + b;
}
staticintadd(inta,intb,intc){
return a +b+c;
}
public static Stringconcatenate(Stringstr1,Stringstr2)
{
return str1 + str2;
}
public static void main(String[] args)
{
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 12
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
int sum1 = add(3, 5);
int sum2 = add(2,4,6);
String result=concatenate("Hello,","Java!");
System.out.println("Sum (two integers): " + sum1);
System.out.println("Sum (three integers): " + sum2);
System.out.println("Concatenation(two strings):"+result);
}
}
Ouput:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 13
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
5. Program to define inheritance and show method overriding.
a) Inheritance:-
class Animal {
public void eat() {
System.out.println("Theanimaleatsfood.");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Thedogbarks.");
}
}
public class InheritanceExample
{
Public static void main(String[] args){
Dog myDog = new Dog();
myDog.eat();
myDog.bark();
}
}
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 14
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Output:-
b) Method Overriding:-
class Shape {
public void draw() {
System.out.println("Drawingashape");
}
}
class Circle extends Shape {
public void draw() {
System.out.println("Drawingacircle");
}
}
public class MethodOverridingExample
{
public static void main(String[] args) {
Circle myCircle = new Circle();
myCircle.draw();
}
}
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 15
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 16
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
6. Write a java program to create a package named pl and and implement this
package in ex1 class.
Step 1: creation of package in java
Step 2: create new folder in c drive named as sravs
Step3: prepare package java program
Package mypack;
Public class A
Public void display()
{
System.out.println(“sravs”);
Step 4: compile this from cmd and create another folder “mypack” in “sravs”
folder
Step5: copy the .class file of above program in “mypack”folder
Step 6: Next prepare java program
import mypack.A;
class pack
Public static void main(String args[])
A x=new A();
Public static void main(String args[]){
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 17
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
A x=new A();
x.display();
Output:
D:\>cd C:\sravs
D:\>C:
C:\sravs>javac A.java
C:\sravs>pack.java
C:\sravs>javac pack.java
C:\sravsas>java pack
sravs
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 18
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
7. Program to demonstrate exception handling in java
a. Exception handling using try...catch Program:-
Class Main{
Public static void main(String[] args)
try
int divideByZero = 5 / 0;
System.out.println("Restofcodeintryblock");
catch(ArithmeticException e)
System.out.println("ArithmeticException=>"+e.getMessage());
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 19
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
b. Java finally block:
Program:-
class Main
{
Public static void main(String[] args)
try
int divideByFive = 10 / 5;
}
catch(ArithmeticExceptione){
System.out.println("ArithmeticException=>"+e.getMessage());
finally
System.out.println("This is the finally block");
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 20
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
c. Java throw and throws keyword Program:-
class Main
{
public static void divideByZero()
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args)
divideByZero();
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 21
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
d. Java throws keyword Program:-
Import java.io.*;
class Main
{
public static void findFile() throws IOException{
File newFile = new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
public static void main(String[] args)
try
{
findFile();
catch(IOExceptione)
System.out.println(e);
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 22
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 23
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
8. Program to demonstrate multithreading in java
a. Extending the Thread class
class MultithreadingDemo extends Thread
public void run()
try
System.out.println("Thread"+Thread.currentThread().getId(+"is running"));
catch(Exception e) {
System.out.println("Exception is caught");
public class Main
public static void main(String[] args)
int n=8;
for (int i=0;i<n;i++)
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 24
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
MultithreadingDemo object=new MultithreadingDemo();
object.start();
}
Output:-
b. Implementing the Runnable Interface
class MultithreadingDemo implements Runnable
public void run()
try
System.out.println("Thread"+Thread.currentThread().getId()+"is running");
catch(Exception e)
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 25
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
System.out.println("Exception is caught");
class Main
public static void main(String[] args)
int n=8;
for(int i=0;i<n;i++)
Threadobject=new Thread(new MultithreadingDemo());
object.start();
}
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 26
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
9. Program to demonstrate i/o operation in java
a. Inputstream
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputStreamDemo
{
Public static void main(String[] args){
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
try{
System.out.print("Enteryourname:");
String name = reader.readLine();
System.out.println("Hello,"+name+"!");
}
catch(IOExceptione)
{
System.out.println("An error occurred while reading input:"+e.getMessage());
finally
try
{
if (reader != null) {
reader.close();
}
}
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 27
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
catch(IOException e)
System.out.println("An error occurred while closing the reader:"+e.getMessage());
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 28
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
b. Output stream
import java.io.FileWriter;
import java.io.IOException
import java.io.PrintWriter;
public class OutputStreamDemo{
public static void main(String[] args){
try(PrintWriter writer=new PrintWriter(new FileWriter("output.txt"))){
writer.println("This is a sample output.");
writer.println("Hello, world!");
System.out.println("Data written to the file.");
}
catch(IOExceptione){
System.out.println("An error occurred while writing to the file:"+e.getMessage());
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 29
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
C. Standard stream
import java.util.Scanner;
public class StandardIOExample{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enteryourname:");
String name = scanner.nextLine();
System.out.print("Enter your age:");
int age = scanner.nextInt();
System.out.println("\nHello,"+name+"!Youare"+age+"yearsold.");
scanner.close();
}
Output :
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 30
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
10. Program to demonstrate network programming in java
a. Socket programming server side java implication
import java.io.*;
import java.net.*;
public class Main{
public static void main(String[] args){
try {
ServerSockets s=new ServerSocket(5000);
System.out.println("Server started");
Socket s = ss.accept();
System.out.println("Clientconnected");
DataInputStreamdis=newDataInputStream(s.getInputStream());
String msg = dis.readUTF();
System.out.println("Clientsays:"+msg);
dis.close();
s.close();
ss.close();
}catch(IOException e)
{ System.out.println(e);
}
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 31
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Output:-
2.Client side java implication
import java.io.*;
import java.net.*;
public class Main{
public static void main(String[]args){
try {
s = new Socket("localhost", 5000);
System.out.println("Connectedtoserver");
DataOutputStreamdos=newDataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a message for the server:");
String msg=br.readLine();
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 32
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
dos.writeUTF(msg);
dos.close();
br.close();
s.close();
catch(IOException e)
System.out.println(e);
}
Output:-
b. URLClass example 1
Import java.net.*;
public class Main{
public static void main(String[] args) throws MalformedURLException
{
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 33
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
URL url = new URL("https://csesvpec.blogspot.com/");
s = url.toString();
System.out.println("URL:"+s);
Output:
Example 2
importjava.net.*;
public class Main{
public static void main(String[]args) throws MalformedURLException
{
URLurl=new URL("https://csesvpec.blogspot.com/");
String protocol = url.getProtocol();
System.out.println("Protocol:"+protocol);
String host = url.getHost();
System.out.println("HostName:"+host);
String fileName = url.getFile();
System.out.println("FileName:"+fileName);
}}
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 34
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Output:
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 35
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
11. Program to demonstrate applet structure and event handling
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener
{ Button b;
TextField tf;
public void init(){
tf=newTextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvente){
tf.setText("Welcome");
}
}
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 36
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Another file:
<html>
<body>
<applet code=”EventApplet” width=”400” height=”300”>
</applet>
</body>
</html>
Output:
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 37
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 38
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
12. Program to demonstrate layout manager
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f=new JFrame();
JButton b1 = newJButton("NORTH");;
JButton b2 = new JButton("SOUTH");;
JButton b3 = new JButton("EAST");;
JButton b4 = new JButton("WEST");;
JButtonb5=newJButton("CENTER");;
f.add(b1, BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3, BorderLayout.EAST);
f.add(b4, BorderLayout.WEST);
f.add(b5, BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
Public static void main(String[] args){
new Border();
}
}
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 39
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Output:-
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 40
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
VIVA Questions:
1. What is the main method?
The main method is the starting point of any Java application. It is required in every Java program.
2.What is a class in Java?
A class in Java is a blueprint for creating objects, which defines the properties and behaviors of an
object. In this case, BasicJavaProgram is the class.
What does System.out.println() do?
System.out.println() is used to print text to the console. It outputs the value and then moves to a new
line.
3.What is the purpose of the Scanner class?
The Scanner class is used for taking input from various sources like the keyboard or a file. In this
example, it is used to take integer input from the user.
4.What are the primitive data types in Java?
Java has 8 primitive data types: byte, short, int, long, float, double, char, boolean.
5.What is the difference between == and equals() in Java?
== compares object references, whereas equals() compares the actual content of the objects (for
objects like String).
6.What is an array in Java?
An array is a collection of elements of the same type, stored in contiguous memory locations.
Explain the use of switch in Java.
The switch statement evaluates an expression and compares it to different case values. It is an
alternative to multiple if-else statements when checking for equality.
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 41
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
7.How does a for loop differ from awhile loop?
In a for loop, the number of iterations is known before the loop starts. In a while loop, the condition
is checked before each iteration, so it can execute any number of times based on the condition.
8.What is a constructor in Java?
A constructor is a special type of method used to initialize an object when it is created. It has the
same name as the class and does not have a return type.
9.What is the difference between a default constructor and a parameterized constructor?
A default constructor is automatically provided by the compiler if no constructors are defined. It
initializes the instance variables with default values (e.g., null for objects, 0 for integers, etc.).
A parameterized constructor is a user-defined constructor that allows you to pass values at the time of
object creation to initialize the object's instance variables with specific values.
10.Can we have multiple constructors in a class?
Yes, this is called constructor overloading. Java allows you to have multiple constructors with
different parameters in the same class. The appropriate constructor is called based on the number and
types of arguments passed when creating the object.
11.What happens if we do not define any constructor in a class?
If no constructor is explicitly defined, Java provides a default constructor that initializes object fields
to default values. However, once you define any constructor (parameterized or not), the default
constructor is no longer provided.
12.Can constructors return a value?
No, constructors do not have a return type. They are used solely to initialize objects.
13.What is constructor overloading?
Constructor overloading occurs when a class has more than one constructor, each with a different
parameter list. The correct constructor is invoked based on the arguments passed during object
creation.
14.What is the purpose of this keyword in constructors?
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 42
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
The this keyword refers to the current instance of the class. It is used to distinguish between instance
variables and parameters when their names are the same. In this program, this.brand, this.model, etc.,
are used to refer to the instance variables of the object.
15.What is Method Overloading?
Method Overloading occurs when there are multiple methods in the same class with the same name
but different parameters (either by number of parameters or types of parameters).
we have multiple add methods:
add(int a, int b) – Adds two integers.
add(int a, int b, int c) – Adds three integers (method overloading with a different number of
parameters).
add(double a, double b) – Adds two double values (method overloading with different parameter
types).
16.What is a Package in Java?
A package is a namespace used to organize classes and interfaces in Java. It helps to avoid name
conflicts and makes the code easier to manage and maintain.
Packages can be built-in (like java.util, java.io) or user-defined.
17.Why use Packages?
Namespace Management: Prevents name conflicts by organizing classes into namespaces.
Code Organization: Helps in logically grouping related classes and interfaces, making the code more
maintainable.
Access Control: Packages provide access protection. Classes in the same package can access each
other’s members (methods and variables) with default access (no modifier), while classes in different
packages need import statements to access them.
18.Why do we import packages?
Importing packages allows you to use predefined classes and methods from external libraries like
Scanner for taking input, or Math for performing mathematical operations.
18.What are some built-in packages in Java?
java.util: Contains classes like ArrayList, HashMap, etc.
java.io: Contains classes for file handling and input/output operations.
java.lang: Automatically imported and contains fundamental classes like String, System, Math, etc.
19.What is the difference between import and package in Java?
package: Used to define the package to which a class belongs.
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 43
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
import: Used to include classes from other packages to use in the current class.
Exception handling in Java allows you to manage runtime errors, ensuring that the program can
continue execution in the event of an error, or at least handle the error gracefully.
20.What is exception handling in Java?
Exception handling is a mechanism in Java that allows you to handle runtime errors or exceptions
that occur during the execution of a program.
21.How do you handle exceptions in Java? What are the different types of exceptions?
Exceptions in Java are handled using try-catch-finally blocks. There are two types of exceptions:
checked exceptions (e.g., IOException) and unchecked exceptions (e.g., NullPointerException).
22.What is multithreading in Java? Explain its benefits.
Multithreading in Java is a technique that allows a program to execute multiple threads or flows of
execution concurrently. Benefits include improved responsiveness, increased throughput, and better
system utilization.
23.How do you create a thread in Java?
A thread in Java can be created by extending the Thread class or implementing the Runnable
interface.
24.What is the difference between byte stream and character stream in Java?
Byte streams in Java are used to read and write raw bytes, while character streams are used to read
and write characters
25.What is socket programming in Java?
Socket programming in Java is a technique that allows a program to communicate with other
programs over a network using sockets.
26.How do you create a socket in Java? What are the different types of sockets?
A socket in Java can be created using the Socket class or the ServerSocket class. There are two types
of sockets: TCP sockets and UDP sockets.
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 44
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
27.What is an applet in Java?
An applet in Java is a small program that runs in a web browser.It is a type of Java program that is
embedded in an HTML page and executed by the browser's Java Virtual Machine (JVM)
28.How do you handle mouse and keyboard events in an applet?
Mouse and keyboard events in an applet can be handled using event listener interfaces, such as
MouseListener and KeyListener.
29.What is a layout manager in Java and types of layout manager
A layout manager in Java is an object that manages the layout of components in a container.
Types of layouts:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. GridBagLayout
5. CardLayout
6. BoxLayout
7. AbsoluteLayout
8. SpringLayout
9. GroupLayout
30.How do you use different layout managers in Java, such as FlowLayout, BorderLayout, and
GridLayout?
Different layout managers in Java can be used by creating an instance of the layout manager class
and setting it as the layout manager for a container using the setLayout() method.
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 45