CS F213 Objected Oriented Programming Labsheet 1
Spring 2024
Write your first JAVA program.
class Hello {
public static void main(String args[]) {
// Program execution begins here
System.out.println("Hello world. I can write Java!");
}
}
Compilation:
Compile your code on a terminal:
javac <YOUR_PROGRAM_NAME>.java
In this case:
javac Hello.java
Execution:
Execute your code through terminal by writing
java <YOUR_PROGRAM_NAME>
In this case:
java Hello
Output:
Hello world. I can write Java!
After your code is compiled, you will find a file with the same name as the class name declared in the file but with the extension .class. A Java class file is a file containing Java bytecode and having .class extension that can be executed by JVM (Java Virtual Machine). A Java class file is created by a Java compiler from .java files as a result of successful compilation. The compilation will result in as many .class files as there are classes in the file you just compiled. A good practice, but not a requirement, is to restrict to one class per java file.
Java Class and Structure
Class:
The Class is the basic unit of Object Oriented Programming. The Class forms the basis for object oriented programming in Java.
General Syntax of a Class:
class classname
{
type instance-variable1;
type instance-variable2;
...
type instance-variableN;
type methodname1(parameter-list)
{ body }
...
type methodnameN(parameter-list)
{ body }
}
Two components of Java Class:
Attributes - Variables
Methods - Functions
Example:
class Square {
int value;
public static void printSquare(int x){
System.out.println(x*x);
}
public static void main(String args[]){
int local_value = 2;
printSquare(local_value);
printSquare(3);
printSquare(local_value*2);
}
}
To instantiate an object of Square:
Square mySquare = new Square();
To access variables of an object
mySquare.value = 12;
To access methods of an object
mySquare.printSquare(10);
Syntax Guidelines
Every line of code that runs in Java must be inside a
class
A good practice is to use CamelCase with the first character capitalised for class names. Class names are usually nouns
A good practice is to use camelCase with the first character in lower case for methods. Method names are usually verbs
The name of the Java file need not match the class name but it is good practice to do so (see Note below).
The
main()
method is required and you will see it in every Java program. Any code inside themain()
method will be executed.
Java Identifiers
All Java variables must be identified with unique names called identifiers.
Declaring (Creating) Variables:
type variableName = value;
Types of Java Literals:
String
- Stores textint
- Stores integers (whole numbers)float
- Stores floating point numberschar
- Stores single charactersboolean
- Stores true or false
Variable Name Guidelines
Variable names are usually in all lowercase but meaningful
Names can contain letters, digits, underscores, and dollar signs
Names must begin with a letter (_ and $ are allowed as the first character but discouraged)
Names should start with a lowercase letter and it cannot contain whitespace
Names are case sensitive
Reserved words (keywords) cannot be used as names
Java Conditional Statements
if
if (condition) {
// block of code to be executed if the condition is true
}
else
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
else if
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
switch
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Shortcut for if-else
variable = (condition) ? expressionTrue : expressionFalse;
Java Loops
while loop
while (condition) {
// code block to be executed
}
do-while loop
do {
// code block to be executed
}
while (condition);
for loop
for (initialization; condition; iteration) {
// code block to be executed
}
for-each loop (can be used for iterating)
for (type variableName : arrayName) {
// code block to be executed
}
Java Data Types
byte
8-bit
Byte-length integer
short
16-bit
Short integer
int
32-bit
Integer
long
64-bit
Long integer
float
32-bit
Single-precision floating point
double
64-bit
Double-precision floating point
char
16-bit
Unicode character A single character
boolean
true or false
A boolean value (true or false)
Array
Declaring an array
elementDataType[] arrayName = new elementDataType[arraySize];
elementDataType[] arrayName = {element_1, element_2, element_3, ..., element_N};
Example
int[] firstArray = new int[10];
int[] firstArray = {0,1,2,3,4,5,6,7,8,9};
Declaring a 2D array
elementDataType[][] arrayName = new elementDataType[rowSize][colSize];
elementDataType[][] arrayName = {{element_1_1, ..., element_1_M}, ..., {element_N_1, ..., element_N_M}};
Example
int[][] firstTwoDArray = new int[10][20];
int[][] firstTwoDArray = {{0,1,2},{3,4,5},{6,7,8}};
Taking input from user
The Scanner class is used to get user input, and it is found in the java.util package.
nextBoolean()
Reads a boolean value from the user
nextByte()
Reads a byte value from the user
nextDouble()
Reads a double value from the user
nextFloat()
Reads a float value from the user
nextInt()
Reads a int value from the user
nextLine()
Reads a String value from the user
nextLong()
Reads a long value from the user
nextShort()
Reads a short value from the user
import java.util.Scanner;
class UserInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("String is: " + str);
int first = sc.nextInt();
int second = sc.nextInt();
int sum = first + second;
System.out.println("Sum is: " + sum);
}
}
Exercise Problems:
Exercise 1
What happens when we declare multiple classes in the same file and then use javac to compile the file and the file name is any one of the declared classes?
Exercise 2
Write a Java program to compute the final amount a person has to repay for a loan of 10 years with interest rate of 5% per annum. The principal amount is to be taken as input from user and display the final amount.
Use double
datatype for principal and final amount.
Formula:
FinalAmount = PrincipalAmount(1 + (TimePeriodInYears * InterestRate / 100))
Input
A double representing the principal amount
Output
A double representing the final amount
Sample Test Input
1000.0
Sample Test Output
1500.0
Exercise 3
Write a Java program to print a menu to the user asking to choose between by entering the corresponding option number:
1. Circle
2. Rectangle
If 1
(circle) is chosen, take the input of radius (int) and print the area of the circle (take pi = 3.14), otherwise take the input of length (int) and breadth (int) of rectangle and print the area.
Do this exercise with both if-else and switch statements.
Sample Test Input 1
1
10
Sample Test Output 1
314.0
Sample Test Input 2
2
60
20
Sample Test Output 2
1200
Exercise 4
Write a Java program to declare a 2D array of size 4 X 3, then take the input from user such that the array contains following elements:
12 3 4
4 34 2
65 1 56
76 24 7
After that, using for-each loop find the sum of the whole array and print it.
***
Last updated