Lab Session 3: Basics of Java Programming Language (2) Objective

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Lab session 3: Basics of Java Programming Language [2]

Objective

The objective of lab session 3 is


 To differentiate instance and static member of the class
 To differentiate primitive and reference data-type
 To use Math and Date classes in Java

Pre-lab Exercise

1. Which of these cannot be declared static?


A. Class C. Object
B. Variable D. Method
2. Which of the following statements are incorrect?
A. Static methods can call other static methods only
B. Static methods must only access static data
C. Static methods can not refer to this or super in any way
D. When object of class is declared, each object contains its own copy of static
variables
3. Which of these methods must be made static?
A. main() C. delete()
B. run() D. finalize()

4. What will be the output of the following Java code?


class access
{
public int x;
static int y;
void cal(int a, int b)
{
x += a ;
y += b;
}
}
class static_specifier
{
public static void main(String args[])
{
access obj1 = new access();
access obj2 = new access();
obj1.x = 0;
obj1.y = 0;
obj1.cal(1, 2);

1|Page
obj2.x = 0;
obj2.cal(2, 3);
System.out.println(obj1.x + " " + obj2.y);
}
}

5. What will be the output of the following Java program?


class static_out
{
static int x;
static int y;
void add(int a , int b)
{
x = a + b;
y = x + b;
}
}
class static_use
{
public static void main(String args[])
{
static_out obj1 = new static_out();
static_out obj2 = new static_out();
int a = 2;
obj1.add(a, a + 1);
obj2.add(5, a);
System.out.println(obj1.x + " " + obj2.y);
}
}

6. What will be the output of the following Java program?


class Student
{
String name;
String checkMyName()
{
return name;
}
}
class static_use
{
public static void main(String args[])
{
Student stud1 = new Student();
stud1.name = "Meron";
System.out.println("Student1 name is:" + stud1.checkMyName());
Student stud2 = stud1;
Stud2.name = "Abdu";
System.out.println("Student2 name is:" + stud2.checkMyName());
}
}

2|Page
Math & Data and Time Class

Methods in Math class are used to perform basic operations such as the elementary
exponential, logarithm, square root, and trigonometric functions.
As such, the java.lang.Math class provides us access to many of these functions. The
table below lists some of the more common among these.
Method Description Arguments
Abs Returns the absolute value of the argument Double, float, int, long
Round Returns the closed int or long (as per the argument) double or float
Ceil Returns the smallest integer that is greater than or equal to Double
the argument
Floor Returns the largest integer that is less than or equal to the Double
argument
Min Returns the smallest of the two arguments Double, float, int, long
max Returns the largest of the two arguments Double, float, int, long

Exponential and Logarithmic methods

Method Description Arguments


exp Returns the base of natural log (e) to the power of argument Double
Log Returns the natural log of the argument double
Pow Takes 2 arguments as input and returns the value of the first Double
argument raised to the power of the second argument
floor Returns the largest integer that is less than or equal to the Double
argument
Sqrt Returns the square root of the argument Double

Java provides the Date class available in java.util package; this class encapsulates the
current date and time.
The Date class supports two constructors
 Date(): this constructor initializes the object with the current date and time.
 Date(long millisec): this constructor accepts an argument that equals the number
of milliseconds that have elapsed since midnight, January 1, 1970.

import java.util.Date;
public 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.toString());
}
}

3|Page
Important Methods
 boolean after(Date date) : Tests if current date is after the given date.
 boolean before(Date date) : Tests if current date is before the given date.
 int compareTo(Date date) : Compares current date with given date. Returns 0 if
the argument Date is equal to the Date; a value less than 0 if the Date is before
the Date argument; and a value greater than 0 if the Date is after the Date
argument.
 long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00
GMT represented by this Date object.
 void setTime(long time) : Changes the current date and time to given time.

Date Formatting Using SimpleDateFormat


SimpleDateFormat (java.text.*) is a concrete class for formatting and parsing dates in a
locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-
defined patterns for date-time formatting.

import java.util.*;
import java.text.*;

public class DateDemo {

public static void main(String args[]) {


Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a");
System.out.println("Current Date: " + ft.format(dNow));
}
}

Simple DateFormat Format Codes


Character Description Example
Y Year in four digits 2021
M Month in year July or 07
d Day in month 04
h Hour in AM/PM (1-12) 12
H Hour in day (0-23) 22
m Minutes in hour 30
s Second in minutes 55
S Millisecond 234
E Day in week Wednesday
D Day in year 360
w Week in year 40
W Week in month 1
A AM/PM marker PM

4|Page
In-lab Exercise

7. Write a Java program to accept a float value of number and return a rounded float
value.
8. Calculate the value of 2.5 raised to the power of 3, using the pow method.
9. (Displaying an integer reversed) Write the following method to display an integer in
reverse order:
public static void reverse(int number)
For example, reverse (3456) displays 6543. Write a test program that prompts the user to
enter an integer and displays its reversal.
10. Write a Java program to display the dates in the specified formats.
Sample Format:
Current date: 2021/08/03
Current date: 03-08-2021

Post-lab Exercise

11. (Math: approximating the square root) Implement the sqrt method. The square root of a
number, num, can be approximated by repeatedly performing a calculation using the
following formula:
nextGuess = (lastGuess + (num / lastGuess)) / 2
When nextGuess and lastGuess are almost identical, nextGuess is the approximated
square root.
The initial guess can be any positive value (e.g., 1). This value will be the starting value for
lastGuess. If the difference between nextGuess and lastGuess is less than a very small
number, such as 0.0001, you can claim that nextGuess is the approximated square root
of num. If not, nextGuess becomes lastGuess and the approximation process continues.

5|Page

You might also like