The purpose of this Lab. is to familiarize student how to solve practical problems programmatically; they will practice on elementary programming using primitive data types, variables, constants, operators, expressions, and input and output. Also, they will learn how to diagnose errors that may occur when a program is compiled or executed. There are some exercises, through which they will understand the concept learn in this chapter.
Activity Outcomes:
Student will learn how to write Java programs to perform simple calculations, they will use Scanner class to obtain input from the console, they will know how to use identifiers to name variables, constants, methods, and classes. The use of constants , Java primitive …show more content…
English will be the official language throughout the discussion.
Names I.D 1. .……………..………………………………. ………………………………
Activity 1: write a program in java to interchange (swap) values of two variables with a use of 3rd variable.
Input: value num1 and num2
Processing: swapping values of num1 to num2 and num2 to num1 using a third variable num3.
Output: Display value of num1 and num2 after swap operation.
Solution:
A. File -> New project-> Project Name: Lab3Activities , Main Class Name Swap2Nos click Finish Button
B. Write Code inside the main method and test it by compiling (F9) and running (Shift + F6) your code.
/* Swap Two Numbers Using Third Vairable*/ public class Swap2Nos { public static void main(String[] args) { // declare variables num1, num2, num3 of the type …show more content…
int i; float f; double d; i = 1; f = 4.4f; d = 5.5; d = i; i = (int)f; f = (float)d;
System.out.println("i = " + i + " f = " + f + " d = " + d);
The above code does the following:
● Converts the value of i to double and stores it in d. This conversion is done automatically by the compiler, because double data type is normally wider than int, there is absolutely no risk storing int in double.
● In the following two statements, notice that we but a large value into a smaller data type, in this case, a possible loss of data occurs in which we have to be aware of. Because that, compiler (by default) refuses to store float value in int, or double in float. Because of that, we use casting to tell to compiler that we know what we are doing!
Another way to convert between variables is using some defined methods that converts between variables.
One of them is a well known method that converts a String to integer which is Integer.parseInt() method, the following example shows how to use it.
String s =