0% found this document useful (0 votes)
71 views62 pages

Java Midterm

The document discusses Java arrays. It explains that arrays are used to store multiple values in a single variable. It shows how to declare and initialize different types of arrays, including integer, string, and other arrays. It also demonstrates how to access array elements by index, change element values, get the array length, and loop through an array.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
71 views62 pages

Java Midterm

The document discusses Java arrays. It explains that arrays are used to store multiple values in a single variable. It shows how to declare and initialize different types of arrays, including integer, string, and other arrays. It also demonstrates how to access array elements by index, change element values, get the array length, and loop through an array.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 62

Java Programming Compilation-Jhustine

 Java Variables

1.

2.

3.

4.
5.
6.

7.
 Java Data types
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power
of 10:

8.
Booleans
A boolean data type is declared with the boolean keyword and can only take the
values true or false:

9.

Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':

10.
Strings
The String data type is used to store a sequence of characters (text). String values must
be surrounded by double quotes:

The String type is so much used and integrated in Java, that some call it "the
special ninth type".

A String in Java is actually a non-primitive data type, because it refers to an object. The
String object has methods that is used to perform certain operations on strings. Don't
worry if you don't understand the term "object" just yet. We will learn more about
strings and objects in a later chapter.

Non-Primitive Data Types


Non-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:

 Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java (except for String).
 Non-primitive types can be used to call methods to perform certain operations,
while primitive types cannot.
 A primitive type has always a value, while non-primitive types can be null.
 A primitive type starts with a lowercase letter, while non-primitive types starts with
an uppercase letter.
 The size of a primitive type depends on the data type, while non-primitive types
have all the same size.

>Java Type Casting

Java Type Casting


Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size
type:

11.

Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of
the value:

12.
>Java Operators

Java Operators
Operators are used to perform operations on variables and values.

The value is called an operand, while the operation (to be performed between the two
operands) is defined by an operator:

13.

Java divides the operators into the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators
14.

15.
16.

Java Assignment Operators


Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a
variable called x:

17.
Java Comparison Operators
Comparison operators are used to compare two values:
18.

Java Logical Operators


Logical operators are used to determine the logic between variables or values:

19.
20. SW no.1 – Create a java program, that will accept a user input for prelim as 30%, midterm as 30%, final as
40% and display the result,

Output-

Prelims:

Midterm:

Final:

Total Grade:
21. Lab1-activity3
22. SW no.2 –lab1 activity2- Find the area of rectangle and its perimeter. Call a method in java . (Create 2
methods)

Output-

Enter Length: Area=lxw

Enter Width: perimeter= (l+w)*2

Area of rectangle is , Perimeter of rectangle is


23. Lab1 activity-1
 Java if else

The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is true.

24. In the example below, we test two values to find out if 20 is greater than 18. If the
condition is true, print some text:
25.

The else Statement


Use the else statement to specify a block of code to be executed if the condition
is false.

26.
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.

27.
Short Hand If...Else (Ternary Operator)
If you have only one statement to execute, one for if, and one for else, you can put it
all on the same line:
 Java Switch

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later in this
chapter

The example below uses the weekday number to calculate the weekday name:

28.
The break Keyword
When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for
more testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest
of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

29.
 Java While Loop

Loops
Loops can execute a block of code as long as a specified condition is reached.

Java While Loop


The while loop loops through a block of code as long as a specified condition is true:

30.

Note: Do not forget to increase the variable used in the condition, otherwise the loop will
never end!
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.

The example below uses a do/while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the condition is
tested:

31.
 Java for loop
Java For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

32.
Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has been
executed.

This example will only print even values between 0 and 10:

33.
34. Lab2a

35. Ass 1 lab2b- Create a java program that will display the following output below
36. Lab2c Create a java program that user will guess the random number generated by computer.
Output:
Guess the number between 1 to 50

Attempt 1: 11 – lower

Attempt 2: 25 – Higher

Attempt 3: 22 – You’ve guess correct answer


37. Sw-
Break and Continue in While Loop
You can also use break and continue in while loops:

Break example:

Continue example:
Chapter 2- Arrays
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.

To declare an array, define the variable type with square brackets:

String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it, we
can use an array literal - place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:


int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

1.
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Array Element


To change the value of a specific element, refer to the index number:

Example
cars[0] = "Opel";

2.

Array Length
To find out how many elements an array has, use the length property:

3.
Loop

Through an Array
You can loop through the array elements with the for loop, and use the length property
to specify how many times the loop should run.

4.
5.
6.

7.
CODE:

package practice1;

import java.util.Scanner;

public class Practice1 {

public static void main (String [ ] args){

Scanner input= new Scanner(System.in);

int count= 1;

double total = 0;

int score[ ] = new int [4];

score[0]= 75;

score [1]= 75;

score [2]= 71;

score [3]= 72;


String [] names ={"Jeremy", "Javier", "Quilloy", "fraga"};

System.out.println();

System.out.printf("Student name \t Test score \n");

for (int i=0; i<score.length; i++){

System.out.printf("%d %s \t %d", count, names[i], score[i]);

System.out.println();

count++;

for (int i=0; i<score.length; i++){

total = total+ score[i];}

double average = total / score.length;

System.out.printf("total average: %.2f" , average);

8.
package practice1;

import java.util.*;

public class Practice1 {

public static void main (String [ ] args){

Scanner input= new Scanner(System.in);

System.out.println("How many numbers you want to enter?");

int n= input.nextInt();

double[] arr = new double[n];

double total = 0;

for(int i=0; i<arr.length; i++){

System.out.print("Enter Element No.");

arr[i] = input.nextDouble();

input.close();

for(int i=0; i<arr.length; i++){

total = total + arr[i];

double average = total / arr.length;


System.out.printf("The average is: %.2f", average);

9. ASS 1- Create a java program that will determine the maximum and minimum value of an array
(Note: pass it to a method)

Sample output:
Enter Size: 3
Enter Num 1: 88
Enter Num 2: 89
Enter Num 3: 90

Max value: 90

Min value: 88
Code:

package practice1;

import java.util.*;

public class Practice1 {

public static void main (String [ ] args){

Scanner input= new Scanner(System.in);

System.out.print("Enter array size:");

int size= input.nextInt();

int arr[]= new int[size];

int count =1;

for(int i=0; i<arr.length; i++){

System.out.printf("Array %d:", count);

arr[i]= input.nextInt();

count++;

input.close();

System.out.println("MinArray:"+ minVal(arr));

System.out.println("MaxArray:"+ maxVal(arr));

static int minVal(int[] array) {

int min= array[0];

for (int i=0; i<array.length; i++)

if(array[i]<min){

min= array[i];

return min;

}
private static int maxVal(int[] array) {

int max= 0;

for (int i=0; i<array.length; i++)

if(array[i]>max){

max= array[i];

return max;

10. Ass 2- Using multi-dimensional Array create a program that will display the output
below.

Basketball tally

1st 2nd 3rd 4th


Team 1: - - - -
Team 2:
If got a tight score “OT” will output
11. Lab Act4a- using a single dimensional array, create a java program that will allow
the user to input the size of an array, inputted a numerical value, get the average
and get the maximum and minimum value (pass the method when getting the max
and min)

Sample output:

Enter Array size: 3

Enter Array 1:

Enter Array2:

Enter Array3:

Enter Array4:

Total size:

Average:

Max Value:

Min Value:
12. labAct4b- Reverse the inputted array.
Output:

Enter Array size: 3

Array1: 5

Array 2: 4

Array 3: 3

Array Input: 5, 4, 3

Reverse Array: 3, 4, 5
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.

To create a two-dimensional array, add each array within its own set of curly braces:

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.

To access the elements of the myNumbers array, specify two indexes: one for the array,
and one for the element inside that array. This example accesses the third element (2) in
the second array (1) of myNumbers:

13.

We can also use a for loop inside another for loop to get the elements of a two-
dimensional array (we still have to point to the two indexes):
14.
Object and Classes
15.
Encapsulation

16. lab5a – create a simple java program using custom class , declare an object that will roll() two dices
with random output.
Setter and Getter
17.
18. Create a java program with setter or getter that the user will input for the field of
program.

Output:
Dog name:
Dog age:
Dog Weight:
Dog Breed:
19. Act5c- Create a java program that will ask for a particular numerical value and
display
The output a factorial.

Sample output:
Enter value: 5
Factorial is 120

Note: Use a loop


20. LabAct 6b.- Inheritance
Inherit the value of Parent class to sub classes. Translate the UML Class diagram
below into a java program.
21. Create an Array List of an employee. Declare a class for our list with getter/ setter create an
override to convert the value into string.
- Inside of our main method/function create another method. Named it print Employee.
- Remove the 1st employee-print employee
- Add another employee – print employee
- Swap any employee position
- Display the employee
package arraylist6a;

import java.util.ArrayList;

public class ArrayList6a {

public static void main(String[] args) {

Employee employee1 = new Employee("John", 28, 25000);

Employee employee2 = new Employee("Smith", 30, 5000);


Employee employee3 = new Employee("Jhust", 19, 80000);

Employee employee4 = new Employee("Tin", 20, 120000);

Employee employee5 = new Employee("Rose", 21, 60000);

ArrayList<Employee> list = new ArrayList<>();

list.add(employee1);

list.add(employee2);

list.add(employee3);

list.add(employee4);

list.add(employee5);

printEmployee(list);

Employee tmp= list.remove(0);

printEmployee(list);

list.add(new Employee("Jhustine",20, 50000));

printEmployee(list);

tmp=list.get(1);

list.set(1, list.get(2));

list.set(2,tmp);

System.out.printf("Employee\tAge\tSalaray\n");

for (Employee emp : list) {

System.out.printf("%s",emp);

public static void printEmployee(ArrayList<Employee>emp){

System.out.print("Name \t Age\t salary\n");

for (Employee e: emp){

System.out.printf("%s",e);}

System.out.println();

}}
package arraylist6a;

public class Employee {

private String name;

private int age;

private double salary;

//constructor

public Employee(String newName, int newAge, double newSalary){

this.name= newName;

this.age=newAge;

this.salary= newSalary;

public void setName(String newName){

this.name=newName;

public String getName(){


return this.name;}

public void setAge(int newAge){

this.age=newAge;

public int getAge(){

return this.age;}

public void setSalary(double newSalary){

this.salary=newSalary;

public double getSalary(){

return this.salary;}

@Override

public String toString(){

return String.format("%s \t\t%d \t%.2f\n",this.name,this.age, this.salary);}

You might also like