Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

LAB 1to 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

Introduction

Object-oriented programming (OOP) is a programming language model organized around


objects rather than "actions" and data rather than logic. Historically, a program has been viewed
as a logical procedure that takes input data, processes it, and produces output data. Object-
oriented programming takes the view that what are really cared about are the objects that is to be
manipulated rather than the logic required to manipulate them.

The first step in OOP is to identify all the objects the programmer wants to manipulate and how
they relate to each other, known as data modeling. Once an object has been identified, it is
generalized as a class of objects which defines the kind of data it contains and any logic
sequences that can manipulate it.

The building of OOP is based on following four pillars.

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

Java
Java is a programming language and a platform based on object-oriented programming concepts.
It was first released by Sun Microsystems in 1995.

There are lots of applications and websites that will not work unless Java is being installed, and
more are created every day. Java is high level, fast, secure, and reliable.

From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the
Internet, Java is everywhere!

Java language will be used throughout this workbook to understand OOP.


Content
Lab
Lab Objective
No.

1 Introduction to Java

2 Java Programming Elements

3 Java Control Statement & Operators

4 Introducing Classes and Objects

5 Overloading & Access Control

6 Arrays & Strings

7 Inheritance in Java

8 Use of abstract and final

9 Packages & Interfaces

10 Exception Handling

11 Introducing JavaFx – Java GUI

12 Exploring JavaFx

13 JavaFx Application

14 Data Storage and Retrieval using filing in Java

15 Introducing UML Diagram


Lab Details
Lab Marks
Lab Objective Signature
No. Obtained

Introduction to Java
1 Objective: Getting familiar with the Java development kit (JDK). Running
your first Java program using CMD and an IDE.

Student Feedback:

Java Programming Elements

2 Objective: Learning Input/Output handling on Java console. Understanding


variables using primitive and non-primitive data types. Exploring Java’s
built in classes.

Student Feedback:

Java Control Statement & Operators


3 Objective: Understanding the control statements of Java including Loops &
if-else. Exploring different operators used in Java.

Student Feedback:

Introducing Classes and Objects


4
Objective: Understanding concepts of class and object in java.
Implementing a class with members including data, methods and
constructors.

Student Feedback:

Overloading & Access Control


5 Objective: Understanding concepts method and constructor overloading.
Learn how to provide different access controls on class members.

Student Feedback:

Arrays & Strings

6 Objective: Understanding Arrays, array index, single and multi-dimensional


arrays, traversing the array using loop. Getting familiar with the String class
of Java.

Student Feedback:

Inheritance in Java
7 Objective: Understanding the concept of inheritance, the superclass and
subclass.

Student Feedback:

Use of abstract and final


8 Objective: Understand the abstract method & class and final method and
class.

Student Feedback:
Packages & Interfaces
9
Objective: Understanding the concept packages & interfaces of Java.

Student Feedback:

Exception Handling
10
Objective: Understand how runtime errors are being handled in Java.

Student Feedback:

Introducing JavaFx– Java GUI


Objective: Understand the design principles of graphical user interfaces
11 (GUIs) using layout managers to arrange GUI components. Understand
basic component of JavaFx and their interaction used in different program
of Java, such as Label, Button, Text Box, Combo Box etc.

Student Feedback:

Exploring JavaFx
12
Objective: Show different JavaFx Layouts and Charts.

Student Feedback:

13 JavaFx Application
Objective: Design a Login page using JavaFx components.

Student Feedback:

Data Storage and Retrieval using Filing in Java


14
Objective: Data storage and retrieval in Signup page using Filing.

Student Feedback:

Introducing UML diagram


15
Objective: Understand the basics of class diagram of UML.

Student Feedback:

Note: Students are advised to write their comments about whether the objective of the lab was achieved in
Student Feedback.

Introduction to Java Lab 1


Objective: Getting familiar with the Java development kit (JDK). Running your first Java program using
CMD and an IDE.

Theory:
What is JDK?
It's the full featured Software Development Kit for Java, including JRE, and the compilers and tools (like Java
Debugger) to create and compile programs.
JRE is required to run Java programs while JDK is required when you have to do some Java programming.

Installing JDK for Windows


1. Download the JDK from Oracle’s website. Choose the right JDK depending upon your system’s
specifications.

Figure 1.1: Download the JDK from Oracle’s website

2. Run the .exe file on your System and follow the steps as given by the installer.
Figure 1.2 Installing JDK

3. Note down the location where j2se has been installed. Java Platform is also called as J2SE (Java 2
Platform Standard Edition)

4. Following screen will appear after successful installation.

Figure 1.3: Successful installation


5. Post installation, you will need to set some environment variables in windows.
6. The path is required to be set for using tools such as javac, java etc.If you are saving the java source
file inside the jdk/bin directory, path is not required to be set because all the tools will be available in
the current directory.But If you are having your java file outside the jdk/bin folder, it is necessary to
set path of JDK.

Setting Java Path

There are 2 ways to set java path:


1. temporary
2. permanent

1. How to set Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow following steps:

 Open command prompt


 Copy the path of jdk/bin directory
 Write in command prompt: set path=copied_path
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin

Let's see it in the figure given below:

Figure 1.4: Command Prompt

2. How to set Permanent Path of JDK in Windows

For setting the permanent path of JDK, you need to follow these steps:
 Go to
MyComputer properties -> advanced tab -> environment variables -> new tab of user variable ->
write path in variable name -> write path of bin folder in variable value -> ok -> ok -> ok

Figure 1.5: Advance System Settings - Windows

 Click on environment variables

Figure 1.6: Set Environment Variables


 Select Path variable and click on Edit button.

Figure 1.7: Set Path Variable

 Copy the path of the bin folder of the JDK and paste it in the variable value field of the path
variable. So add ";C:\Program Files\Java\jdk1.7.0_02\bin" in the path string.

Figure 1.8: Edit System Variable

 Click OK... to finish.


 Now your permanent path is set. You can now execute any program of java from any drive.

Note:
The PATH environment variable is a series of directories separated by semicolons (;) and is notcase-
sensitive. Microsoft Windows looks for programs in the PATH directories in order, from left to right.
The new path takes effect in each new command window you open after setting the PATH variable.
Lab Task:

Write a simple program in java, compile and run it using cmd.

1. Open notepad and type the content.

class HelloWorld {
public static void main(String args[]){
System.out.println(“Hello World!!”);
}
}

2. Save it as HelloWorld.java. Naming is strictly case-sensitive; make sure you type as it is given above.
3. Now open a command prompt and change to the directory where you have saved HelloWorld.java
4. Enter SET CLASSPATH.
5. Press enter; this sets the classloader path to search for class files in the current directory.
6. Type the command javac to compile your code. If the compilation is successful, you would not be
shown any errors.
javac HelloWorld.java
Type the command java HelloWorld and press enter. Please note that you did not include any
extension such as .java or .class to the class name you wish to run.
javaHelloWorld
7. You would get nice output greeting “Hello World!!”

What is an IDE?

An integrated development environment (IDE) is a software application that provides comprehensive


facilities to computer programmers for software development. An IDE mayconsist of a source code editor;
build automation tools,compiler and a debugger.

There are different IDE’s used for Java development including NetBeans and Eclipse.

Before starting to develop the complex programs, you need an IDE. In this workbook we will be using
Eclipse IDE for code writing, compilation and execution.

Install Eclipse IDE


Download Eclipse form its official website and install it on your system by following the instruction provided
by the installer.

Figure 1.9: Download Eclipse IDE

After installation, open eclipse. You will see the welcome screen.

Figure 1.10: Welcome Screen of Eclipse

Write a simple program in java, compile and run it using IDE.

 Create new project in eclipse. Click on file menu, select Project, then select Java Project and click
Next. You will see the following screen. Give your project a name and click Finish.
Figure 1.11: Creating new project in Eclipse

 Now right click on your project available in project explorer and create new class.
Figure 1.12: Add new Class

 A window similar to one shown below will appear. Enter the class name and check the checkbox for
public static void main (String[] args). Click finish.

Figure 1.13: Creating new Class

 A java file will open with some added code. Just add the following line inside the main()
method.System.out.println("Hello World!!");
Figure 1.14: Adding Java Code

 Save the file.


 Now compile and execute this code. In Eclipse compilation and Execution performs by clicking the
button highlighted in the image below.

Figure 1.15: compile& Execute

 The output of this code will be generated in the console window present below.
Figure 1.16: Console Output

Lab Assignment:
1. Write a simple java program with command-line argument in java.

Java Programming Elements Lab 2


Objective:Learning Input/Output handling on Java console. Understanding variables using primitive and non-
primitive data types. Exploring Java’s built in classes.

Theory:
Console input
System.in to the standard input device. Console input is not directly supported in Java, but Scanner class is
used to create an object to read input from System.in, as follows:
Scanner input = new Scanner(System.in);
double radius = input.nextDouble();

Import the class by adding


import java.util.Scanner;

Console output
Java uses System.out to refer to the standard output device.To perform console output, println method is used
to display a primitive value or a string to the console.
System.out.print("Hello ");
System.out.println("world");

You can use the System.out.printf method to display formatted output on the console.
System.out.printf(“Your Total amount is %4.2f", total);
System.out.printf("count is %d and amount is %f", count, amount);

Data Types in Java


A data type in a programming language is a set of data with values having predefined characteristics.
There are two basic types in Java.
1. Primitive
A primitive type is predefined by the language and is named by a reserved keyword.
2. Non-Primitive
It is a reference data type, which are references to objects.

Figure 2.1: Data Types in Java


Variables

Variable is a name of memory location.


It is name of reserved area allocated in memory.
In the given example; int is data type, a is variable name
and 10 is the value that a variable holds, followed by a terminator;

Figure 2.2: Variable Initialization


Type Conversion
Casting is an operation that converts a value of one data type into a value of another data type. The syntax
for casting a type is to specify the target type in parentheses, followed by thevariable’s name or the value
to be cast. For example;

System.out.println((int)1.7);

The above statement displays 1. When a double value is cast into an int value, the fractional part is
truncated.

Some Useful Java Classes

Math
Math class file is included for the definitions of math functions listed below. It is written as
java.lang.Math.

Trignometic / Maths Functions


 sin(n)  hosh(n)
 cos(n)  tanh(n)
 tan(n)  pow(nmb,pwr)
 sinh(n)  sqrt(n)

Date
Java provides a system-independent
encapsulation of date and time in the
java.util.Date class. The no-arg
constructor of the Date class can be
used to create an instance for the
current date and time.
Lab Task:
1. Write a Java program to take different input from user and store the input in variables with
respective data type and then display the data on the console.

import java.util.Scanner;

public class HelloWorld {

public static void main(String[] args)


{
String name;
char gender;
int age;
double height;

Scanner input = new Scanner(System.in);

System.out.println("Enter Name: ");


name = input.nextLine();

System.out.println("Enter Gender(M/F): ");


gender = input.next().charAt(0);

System.out.println("Enter Age: ");


age = input.nextInt();

System.out.println("Enter Height: ");


height = input.nextDouble();

System.out.println(" ______ Student Data ______\n");

System.out.println("\t Name: " + name);


System.out.println("\t Gender: " + gender );
System.out.println("\t Age: " + age);
System.out.println("\t Height: " + height);

}
}

2. Write a Java program to explore Math class.

public class MathClass


{
public static void main(String[] args)
{
double a=45,b=1,sn,cs,tn,snh,csh,tnh;
sn=Math.sin(a);
cs=Math.cos(a);
tn=Math.tan(a);
snh=Math.sinh(b);
csh=Math.cosh(b);
tnh=Math.tanh(b);

System.out.println("\nTrignometric Functions");
System.out.println("sin 45 = " + sn);
System.out.println("cos 45 =" + cs);
System.out.println("tan 45 =" + tn);

System.out.println("\nHyperbolic Functions");
System.out.println("sinh 1 = " + snh);
System.out.println("cosh 1 = " + csh);
System.out.println("tanh 1 = " + tnh);

}
}

3. Write a Java program to explore Date class.

import java.util.Date;
class DateDemo
{
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date);
// Display number of milliseconds since midnight, January 1, 1970
long msec = date.getTime();
System.out.println("Milliseconds since Jan. 1, 1970 " + msec);
}
}

Lab Assignment:
1. Program the following.

Implement the following equation

3x4sin(180x) + 4x3cos(90x) + x2sin(tan(45)) + 7x + 9cos(90x2 )

Where x may be user defined value.


Java Control Statement & Operators Lab 3

Objective:Understanding the control statements of Java including Loops & if-else.Exploring different
operators used in Java.

Theory:
IterationStatements
A loop can be used to tell a program to execute statements repeatedly.Java provides a powerful construct
called a loop that controls how many times an operation or a sequence of operations is performed in
succession.A loop can be nested inside another loop.Different form of loops can be nested with one another.

Java provides three types of loop statements:

1. while loops,
2. do-while loops, and
3. for loops.

Loop Syntax

while do-while for

while (loop- do { for (initial-action;


continuation-
condition) // Loop body; Statement(s); loop-continuation-
condition;
{ }
action-after-each-
// Loop body while (loop-continuation- iteration)
Statement(s); condition);
{
}
// Loop body;
Statement(s);

Selection Statements
Selection Statements of Java programming language decides the next statement for execution.Selection
statements use conditions that are Boolean expressions.A Boolean expression is an expression that evaluates
to a Boolean value: true or false.An if statement can be inside another if statement to form a nested if
statement.

Java provides three types of selection statements:


1. If statements
2. If-else statements
3. If-else if
4. Switch

if statement executes the statements if the condition is true. if-else statement is two way statement that
decides which statements to execute based on whether the condition is true or false. Multi-way if-else
statement is the preferred coding style for multiple alternative if statements.

If-else Syntax

if do-while for

if (boolean- if (boolean-expression) if (boolean-expression)


expression)
{ {
{ //for-the-true-case; // for-1st-case;
statement(s);
} }
} else { else if(boolean-expression)
{
//for-the-false-case;
// for-2nd-case;
}
}

else {

//for-default-case;

Switch Syntax

switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
casevalueN:
// statement sequence
break;
default:
// default statement sequence
}

Operators in Java
There are many operators provide by Java. Following are the most commonly used operators.

Comparison Operators:
Comparison operators can be used to compare two values. The result of the comparison is a Boolean value:
true or false. Java provides six comparison operators.

Figure 2.3: Comparison Operators

LogicalOperators:
The logical can be used to create a compound Boolean expression. Sometimes, whether a statement is
executed is determined by a combination of several conditions.

Figure 2.3: Boolean Operators

Lab Task:
1. Write a Java program to use an if-else-if ladder to determine which season a particular month
is in.

// Demonstrate if-else-if statements.


classIfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Invalid Month";
System.out.println("April is in the " + season + ".");
}
}
2. Write a Java program to generate following pattern.

..........

// Loops may be nested. .........


class Nested {
public static void main(String args[]) { ........
inti, j;
for(i=0; i<10; i++) { .......
for(j=i; j<10; j++)
System.out.print("."); ......
System.out.println();
} .....
}
} ....

...

..

Lab Assignment:
1. Write a program 1 of this lab using switch statement.

2. The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are
1, 1. Every subsequent value is the sum of the 2 values preceding it. Write a Java Program that
print the nth value of the Fibonacci sequence?

3. Write a Java program that prompts the user for an integer and then prints out all the prime
numbers up to that Integer?
Classes & Objects Lab 4

Objective: Understanding concepts of class and object in java. Implementing a class with members
including data, methods and constructors.

Theory:
Class
A class consists of
 Data(variables)
 Methods
 Constructors

Lab Task:
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
}
// ___________ Demo Class ___________
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Adding Constructor

class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

Lab Assignment:

1. Create a class Calculator with following details;

 The class should contain default and parameterized constructor. The constructors should just print
the statement as follows.
 “Inside Default Constructor”
 “Inside Parameterized Constructor”.

 The class should contain following data fields and methods;


 int square = 2 ;
 int cube = 3;

 calculateSquare(int x)
 calculateCube(int x)
 calculateFactorial (int x)
 generateTable(int x)

 Create objects of this class using both Constructors in main Class.


 Call all three functions via object.

You might also like