0% found this document useful (0 votes)
7 views14 pages

Java OOP Programming Activities Compilation

This document contains Java programming code examples and explanations for various Java concepts including arithmetic, arrays, conditional statements, switch statements, loops (while, do-while, for), and the for-each loop. It was submitted by John Mark Monterde to his professor Engr. Val S. Mangalino of Holy Trinity University in partial fulfillment of the requirements for a Bachelor of Science degree in Computer Engineering.

Uploaded by

valmangalino15
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views14 pages

Java OOP Programming Activities Compilation

This document contains Java programming code examples and explanations for various Java concepts including arithmetic, arrays, conditional statements, switch statements, loops (while, do-while, for), and the for-each loop. It was submitted by John Mark Monterde to his professor Engr. Val S. Mangalino of Holy Trinity University in partial fulfillment of the requirements for a Bachelor of Science degree in Computer Engineering.

Uploaded by

valmangalino15
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Holy Trinity University

Programming Compilations for Object Oriented Programming

Presented to:
Engr. Val S. Mangalino

In Partial Fulfillment of the Course Requirement


For the degree of Bachelor of Science in
Computer Engineering

By:

John Mark Monterde

January 22, 2023


Java Activities Compilations:

Java Arithmetic

package java_compilations;

import [Link];
public class Java01_Arithmetic {
public static void main(String[] args) {
float num1;
float num2;
float result;

Scanner scan = new Scanner([Link]);

[Link]("Please Enter a Number: ");


num1 = [Link]();

[Link]("Please Enter a 2nd Number: ");


num2 = [Link]();

result = num1 + num2;


[Link](result);

Java Arrays

package java_compilations;

import [Link];
public class Java02_Arrays{

public static void main (String [] args){

// Array w Values
String mugiwara [] = {"Luffy", "Zoro", "Nami", "Sanji"};
int evennum [] = {2, 4, 6, 8, 10};

// Array wo Values
String yonko [] = new String [4];
int bounty [] = new int [4];

//Accessing Arrays
[Link](mugiwara[0]);
[Link](evennum[3]);
[Link](evennum[0] + evennum[4]);

mugiwara [3] = "Chopper";


[Link](mugiwara[3]);

Scanner x = new Scanner([Link]);


String Sichibukai [] = new String [7];

[Link]("Enter a warlord: ");


Sichibukai [1] = [Link]();

[Link](Sichibukai[1]);
//Challenge
String Email [] = {"monterdejohnmark0@[Link]", "macmain2312@[Link]",
"xoxadboi@[Link]", "h2big69@[Link]",
"makku.dayo23@[Link]"};

String Username [] = {"MJM", "MM", "XXB", "H2B", "MD"};

String Password [] = {"Monterde123", "jmmntrd69", "onepieceisreal",


"Xcdxero23", "Kariman23"};

[Link]("Email: " +Email[0]+ "---Username: " +Username[0]+ "---


Password: " +Password [0]);
[Link]("Email: " +Email[1]+ "---Username: " +Username[1]+ "---
Password: " +Password [1]);
[Link]("Email: " +Email[2]+ "---Username: " +Username[2]+ "---
Password: " +Password [2]);
[Link]("Email: " +Email[3]+ "---Username: " +Username[3]+ "---
Password: " +Password [3]);
[Link]("Email: " +Email[4]+ "---Username: " +Username[4]+ "---
Password: " +Password [4]);

}
}
Java Conditional Statement

package java_compilations;

import [Link];
public class Java03_Conditional_Statement {
public static void main (String [] args){
Scanner Y = new Scanner([Link]);

[Link]("Please Enter your Name: ");


String Name = [Link]();
[Link]("Hello " +Name);

Scanner X = new Scanner([Link]);

[Link]("Please Enter your age: ");


int age = [Link]();

if (age >=18){
[Link]("You are an Adult");

} else {
[Link]("You are a Teenager");

Scanner Z = new Scanner([Link]);

[Link]("Please a Number");
int Grade = [Link]();

if (Grade >=75){
[Link]("You have an Excellent Grade!");

} else if (Grade <75){


[Link]("You have passed the subject");
} else{
[Link]("Error occured");

}
}
Java Switch Statement

package java_compilations;

import [Link];

public class Java04_Switch_Statement {


public static void main (String[] args){

//switch state are only for strings, char, int

Scanner x = new Scanner([Link]);

[Link]("Please Enter a Month: ");


int month = [Link]();

[Link]("Please Enter a Date: ");


int date = [Link]();

[Link]("Please Enter a Year: ");


int year = [Link]();

String MONTH = "";

switch(month){
case 1:
MONTH = ("January");
break;
case 2:
MONTH = ("February");
break;
case 3:
MONTH = ("March");
break;
case 4:
MONTH = ("April");
break;
case 5:
MONTH = ("May");
break;
case 6:
MONTH = ("June");
break;
case 7:
MONTH = ("July");
break;
case 8:
MONTH = ("August");
break;
case 9:
MONTH = ("September");
break;
case 10:
MONTH = ("October");
break;
case 11:
MONTH = ("November");
break;
case 12:
MONTH = ("December");
break;
default:

}
[Link]();

if (MONTH == "") {
[Link]("Invalid Month");
}else if (date > 31 || date <=0)
[Link]("Invalid Date");
else [Link](MONTH + " "+ date + ", " + year);

}
}

Java While and Do-While Loop

package java_compilations;

import [Link];
public class Java05_While_and_Do_While_Loop {

public static void main (String[] args){

//While Loop
String[] fruits ={"Banana","Mango", "Grapes",
"Apple", "Orange", "Watermelon",
"Pineapple", "Star Fruit", "Rambutan"};
[Link]([Link]);
int x =0 ;
while(x < [Link]){
[Link](fruits[x]);
x++;
}

//Do-While Loop

int y =0;

do {
[Link](y);
y++;
}while(y < 5);

//Conditional While Loop

Scanner s = new Scanner([Link]);


String[] fruitss ={"Banana","Mango", "Grapes",
"Apple", "Orange", "Watermelon",
"Pineapple", "Star Fruit", "Rambutan"};
[Link]("Fruit to Search: ");
String search = [Link]();

int z = 0;
while(z < [Link]){

if(fruitss[z].equalsIgnoreCase(search)){
[Link]("Fruit Found " + fruitss[z]);
break;
}
z++;
}

// Quiz Game
Scanner q = new Scanner([Link]);

int lives = 3;
int answer;
while(lives >0) {

[Link]("Solve this math question:" +


"3(2+1)/3");
[Link]("Answer: ");
answer = [Link]();

if(answer == 3) {
[Link]("Ang galing!");
break;
}
else lives--;
[Link]("Wrong, you only have 2 lives left");

}
Java For Loop

package java_compilations;

public class Java06_For_Loop {

public static void main (String[] args){

// //For Loop - specialize for iterating arrays


//
// Scanner scanner = new Scanner([Link]);
//
// String[] names={"James", "Chauncey", "Cedric", "Patrick", "John Mark",
// "Nidoy", "Keith", "kent"};
// [Link]("Enter Name: ");
// String yourName = [Link]();
//
//
//
// for (int x =0; x< [Link];x++ ){
//
// if (names[x].equalsIgnoreCase(yourName)){
// [Link](names[x]+", you are on the list");
// break;
//
// } else {
// [Link](names[x]+", does not exist on the list.");
//
//
// }
// }

// //User Authentication Programm


// Scanner scanner = new Scanner([Link]);
//
// String[] ListOfUsernames = {"makk23", "[Link]", "patty.v", "[Link]"};
// String[] ListOfPasswords = {"jmmntrd69", "arbisSupot2003", "pattyQTuwu",
"supotAko"};
//
// [Link]("Enter Username: ");
// String username = [Link]();
//
// [Link]("Enter Password: ");
// String password = [Link]();
//
// for (int x = 0; x<[Link]; x++){
//
// if ([Link](ListOfUsernames[x]) &&
[Link](ListOfPasswords[x])){
// [Link]("Welcome, "+ListOfUsernames[x]);
// break;
// }
// }

// Scanner scanner = new Scanner([Link]);


//
// String [] ListOfNames = {"Obed", "Jotham", "Kent", "Aron", "Mark"};
//
// [Link]("Search Name: ");
// String search = [Link]();
// boolean found = false;
//
// for(int x = 0; x<[Link]; x++){
//
// if([Link](ListOfNames[x])){
// [Link](ListOfNames[x]+ " is on the list");
// found = true;
// break;
// }
//
// }
//
//
// if (!found){
// [Link](search+ " is not on the list");
// }

}
}

Java For Each Loop

package java_compilations;

public class Java06_For_Loop {

public static void main (String[] args){

// //For Loop - specialize for iterating arrays


//
// Scanner scanner = new Scanner([Link]);
//
// String[] names={"James", "Chauncey", "Cedric", "Patrick", "John Mark",
// "Nidoy", "Keith", "kent"};
// [Link]("Enter Name: ");
// String yourName = [Link]();
//
//
//
// for (int x =0; x< [Link];x++ ){
//
// if (names[x].equalsIgnoreCase(yourName)){
// [Link](names[x]+", you are on the list");
// break;
//
// } else {
// [Link](names[x]+", does not exist on the list.");
//
//
// }
// }

// //User Authentication Programm


// Scanner scanner = new Scanner([Link]);
//
// String[] ListOfUsernames = {"makk23", "[Link]", "patty.v", "[Link]"};
// String[] ListOfPasswords = {"jmmntrd69", "arbisSupot2003", "pattyQTuwu",
"supotAko"};
//
// [Link]("Enter Username: ");
// String username = [Link]();
//
// [Link]("Enter Password: ");
// String password = [Link]();
//
// for (int x = 0; x<[Link]; x++){
//
// if ([Link](ListOfUsernames[x]) &&
[Link](ListOfPasswords[x])){
// [Link]("Welcome, "+ListOfUsernames[x]);
// break;
// }
// }

// Scanner scanner = new Scanner([Link]);


//
// String [] ListOfNames = {"Obed", "Jotham", "Kent", "Aron", "Mark"};
//
// [Link]("Search Name: ");
// String search = [Link]();
// boolean found = false;
//
// for(int x = 0; x<[Link]; x++){
//
// if([Link](ListOfNames[x])){
// [Link](ListOfNames[x]+ " is on the list");
// found = true;
// break;
// }
//
// }
//
//
// if (!found){
// [Link](search+ " is not on the list");
// }

}
}
Java Nested For Each Loop

package java_compilations;

public class Java08_Nested_For_and_For_Each_Loop {

public static void main(String[] args) {

//2D Arrays

String names[][] = {
{"Mac", "Mac2323"},
{"John", "john123"},
{"Luffy", "luffy11"},
{"Zoro", "zoro44"}

};

int numbers[][] = new int[4][3];

[Link](names[0][1]);

//NESTED FOR LOOP

for (int x = 0; x < 10; x++) {

for (int y = 0; y < 10; y++) {


[Link](x + " " + y);
}
}

[Link]();

//ITERATING ARRAY

String Namesss[][] = {
{"Mac", "Mac2323"},
{"John", "john123"},
{"Luffy", "luffy11", "hitohito"},
{"Zoro", "zoro44", "santoryu", "onigiri"}

};

for (int row = 0; row < [Link]; row++) {

for (int col = 0; col < Namesss[row].length; col++) {


[Link](row + " " + col);
}

[Link]();

// //2D Arrays
// String names [][] = {
// {"Mak", "Monterde"},
// {"Obed", "De Belen"},
// {"Aron", "Palmera"},
// {"Jotham", "Rosete"},
// };
//
// //Assigning and Modifying 2D Arrays
// names[2][0] ="Kevin";
// [Link](names[2][0]);
//
// //Nested For Loop
//
// for (int x =0; x<5; x++){
//
// for (int y =0; y<5;y++){
// [Link](x+ " : " +y);
// }
// [Link]();
// }

//Iterating 2D Arrays

// String[][] names = {
// //col 0 col1
// {"Obed", "De Belen"}, //row 0
// {"Jotham", "Rosete"}, //row 1
// {"Kent", "Dela Cruz"}, //row2
// {"Mark", "Monterde"}, //row3
// };
//
//
// //NESTED For Loop
// for (int row = 0; row<[Link]; row++){
//
// for (int col = 0; col<names[row].length; col++){
// [Link](row+ " : " +col);
// }
// [Link]();
// }

//NESTED For-Each Loop


// String[][] names = {
// //col 0 col1
// {"Obed", "De Belen"}, //row 0
// {"Jotham", "Rosete"}, //row 1
// {"Kent", "Dela Cruz"}, //row2
// {"Mark", "Monterde"}, //row3
// };
//
// for (String firstName[]: names){
//
// for (String LastName:firstName){
// [Link](LastName);
//
// }
// [Link]();
// }

}
}
Java Methods

package java_compilations;

public class Java09_Methods {

//Global Variable - accessible to all


static String fruit = "Apple";

public static void main(String[] args) {

//calling methods
hello();

//Local Variable - only accessible inside a block of code.


String name = "Makkk";
[Link](fruit); // Global variable "fruit"

//calling methods with arguments


print("Hello World!");

add(1,2); // adds num1 & num2

info("John Mark", 20, "El Nido, Palawan");

//methods
static void hello(){
print("Hello");
}

static void printfruit(){


print(fruit); // Global variable "Fruit"
}

//Methods with Arguments


//you can also call methods inside a methods(Ang galing!)
// the "print method below has 6 usages
static void print(String words){
[Link](words);
}

static void add(int num1, int num2){


[Link](num1 + num2);
}

static void info(String name, int age, String address){


print("Name: "+name);
print("Age: "+age+ " years old");
print("Address: "+address);
}

}
Java Packages

package java_compilations;

import packages.*;
public class Java10_Packages {
public static void main(String[] args){

//Packages

//class instantiation
arithmetics arith = new arithmetics();

//Accessing Modifiers
int Addition = [Link](3,2);
printN(Addition);

int Subtraction = [Link](3,2);


printN(Subtraction);

int Multiplication =[Link](3,2);


printN(Multiplication);

int Division = [Link](6,3);


printN(Division);

static void printS(String word){


[Link](word);
}

static void printN(int num){


[Link](num);
}

Common questions

Powered by AI

The Java Scanner class simplifies input handling by providing methods to read various data types directly from the console. This makes it a user-friendly way of handling input for interactive applications . However, it may introduce performance issues when processing large datasets due to its use of regular expressions internally. Moreover, improper input validation could cause the program to crash or behave unpredictably if unexpected data types are entered. An improvement would be implementing validations and error handling or using Java's NIO package for more efficient input handling.

The switch statement in Java handles invalid month inputs by assigning an empty string to the MONTH variable if the month is not within the range of 1 to 12. If the MONTH remains an empty string after checking the cases, it outputs 'Invalid Month' . To improve handling, the method could be modified to include validation before entering the switch statement to immediately return an error for invalid numeric ranges; additionally, using enums and exception handling could provide more robust solutions.

Initializing arrays with predefined values is crucial to avoid accessing null or uninitialized elements, which can lead to runtime errors. Predefined values ensure that when elements are accessed, they possess expected data types and values, minimizing unexpected behavior during program execution. This practice leads to more predictable and manageable code, allowing easier debugging and validation of algorithms as demonstrated with the 'mugiwara' and 'evennum' arrays .

Global variables, defined outside methods, are accessible to all methods within the class, providing a consistent state and reducing the need to pass data between methods. Local variables, defined within methods, limit scope to enclosed blocks ensuring data is not accessible outside the method it is declared in, enhancing modularity and preventing unintended interactions . Local variables help in maintaining encapsulation, while global variables ensure consistent access across methods.

The conditional while loop in Java is used to iteratively check each element in an array against a search term using the equalsIgnoreCase method until a match is found or the array is exhausted. This process helps in searching without knowing the index beforehand . Potential improvements include using a hash set for faster lookup times when dealing with large data or using streams in Java 8 for cleaner and more declarative syntax.

Logical flow in programming ensures that operations occur in a meaningful sequence and that inputs lead to expected results. User input validation is a critical component as it prevents incorrect data from affecting program flow, demonstrated by checking user ages or month validity before proceeding . Accurate flow control structures, such as if statements, loops, and switch cases, manage the program's sequence, making it predictable and reliable. These practices enhance robustness, security, and overall program stability, ultimately leading to successful task fulfillment.

A do-while loop is beneficial in scenarios where the code block must execute at least once regardless of the condition. This loop structure is useful when an initial action needs to be performed before the loop condition is evaluated, such as in menu-driven applications where a prompt must be displayed or calculations performed before a user decides to continue or exit . Conversely, a regular while loop evaluates the condition before execution, which might bypass the block entirely if the condition is initially false.

User-defined methods improve code reusability by encapsulating common operations into a single block of code, allowing them to be reused across the project with different parameters while maintaining consistency . This organization forms a modular code structure, making the program easier to manage, debug, and extend. Methods can simplify complex problems by breaking them into smaller, manageable sub-tasks, thus improving comprehension and collaboration across development teams.

Switch statements offer a more readable and efficient alternative to multiple if-else statements when evaluating an expression against many possible constant values. They enhance code maintainability by clearly delineating distinct cases and can lead to performance benefits as Java often optimizes switch statements into jump tables for large numbers of cases. This structure also reduces redundancy and improves error-checking due to the distinct and separate paths of execution provided for each case .

Nested for loops are essential for processing 2D arrays because they allow iteration through each element in both dimensions: rows and columns. A single loop can only traverse one dimension, making it insufficient for accessing the entire grid of a 2D array. Using nested loops, each loop controls one dimension—the outer loop for rows and the inner loop for columns—thereby enabling comprehensive access and manipulation of every element in the 2D structure .

You might also like