An array is a static data structure storing data of the same type. There are three types of arrays, but a three-dimensional array is used for machine learning or deep learning, so in this post, we will cover one-dimensional array and two-dimensional array.
One-dimensional array
One dimensional array is used primarily when no value is defined to be stored in the array.
To make a new array : format
Datatype [] = new Datatype[Size of Array]. Here, the size of the array[] means how many rooms this array has.
int[] score = new int[3];
There are two formats of one-dimensional array.
First format
int[] score = new int[3];
System.out.println(score[0]);
System.out.println(score[1]);
System.out.println(score[2]);
// To assign a new value
score[0] = 80;
score[1] = 90;
score[2] = 100;
System.out.println(score[0]);
System.out.println(score[1]);
System.out.println(score[2]);
//Initial value : 0
//double
double[] d = new double[3];
System.out.println(d[0]);
System.out.println(d[1]);
System.out.println(d[2]);
// Initial value : 0.0
//char
char[] c = new char[3];
System.out.println(c[0]);
System.out.println(c[1]);
System.out.println(c[2]);
// There is no initial value
//boolean형
boolean[] b = new boolean[3];
System.out.println(b[0]);
System.out.println(b[1]);
System.out.println(b[2]);
// Initial value : false
//Reference type : String
String[] str = new String[3];
System.out.println(str[0]);
System.out.println(str[1]);
System.out.println(str[2]);
// Initial value : null
str[0] = "Jave";
str[1] = "Oracle";
str[2] = "Spring";
System.out.println(str[0]);
System.out.println(str[1]);
System.out.println(str[2]);
Second format
This format is used when the declaration of the array and the value's initialization happen simultaneously. When there are certain values that you want to assign first, you can use this.
The most important thing to remember when it comes to arrays is that you can't put different datatypes in the same array.
As you can see, array is a very efficient way to write a simple and clean code.
import java.util.Scanner;
public class ArrayEx03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] s = new int[5];
System.out.println("Enter your scores of the 5 subjects.");
Scanner sc = new Scanner(System.in);
int sum = 0;
for(int i=0; i<s.length; i++) {
s[i] = sc.nextInt();
sum += s[i];
}
double avg = sum / 5.0;
System.out.println("Sum:"+ sum);
System.out.println("Avg:"+ avg);
}
}
Example : Max and Min number
public class ArrayEx04 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double[] data = {9.5, 7.0, 13.6, 7.5, 10.5};
double max, min;
max = data[0];
min = data[0];
for(int i=1; i<data.length; i++) {
if(data[i] > max) max = data[i];
if(data[i] < min) min = data[i];
}
System.out.println("max:"+max);
System.out.println("min:"+min);
}
}
Two-dimensional array
Two-dimensional array sounds more difficult, but the basic is same as one dimensional array.
Let's check out the codes first.
So, let's say there are three five students who took exams of three subjects and we are arranging the scores in the two-dimensional array.
public class ArrEx {
public static void main(String[] args) {
int [][]score=new int [5][3]; // datatype [row] [col]
score[0][0]=10; score[0][1]=90; score[0][2]=70;
score[1][0]=60; score[1][1]=80; score[1][2]=65;
score[2][0]=55; score[2][1]=60; score[2][2]=85;
score[3][0]=90; score[3][1]=75; score[3][2]=95;
score[4][0]=60; score[4][1]=30; score[4][2]=80;
//For loop
for(row = 0; row < 5 ; row++){
for(col = 0; col < 3 ; col++){
System.out.print(" " +score[row][col]);
}
System.out.println("");
}
}
}
Compare to not using array, it will be still clean but this code looks a bit too much work.
Let us elaborate this little bit better.
public class ArrEx01 {
public static void main(String[] args) {
int [][]score = { { 85, 60, 70}, //row no.0
{ 90, 95, 80}, //1
{ 75, 80, 100}, //2
{ 80, 70, 95}, //3
{100, 65, 80} //4
};
int [] subject = new int[3];
int [] student = new int[5];
int r, c;
System.out.println("Sum by each subjects. ");
for(c = 0; c < 3 ; c++){ // subjects
for(r = 0; r < 5 ; r++){ // students
subject[c] += score[r][c];
}
System.out.println(subject[c]);
}
System.out.println("Sum by each studetns");
for(r = 0; r < 5 ; r++){ // studnets
for(c = 0; c < 3 ; c++){ // sujects
student[r] += score[r][c];
}
System.out.println(student[r]);
}
}//main() end
}// class end
Type Conversion in array
In Java, type conversion is a very important thing to remember because it happends a lot everytime. We will talk about this in the other posts, but now, just take a peek of how they look like.
public class ArrayEx07 {
//Absolute value
static int abs(int data) {
if(data < 0)
data = -data;
return data;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// args[0] = " -10", args[1] = "-20" => char
System.out.println("args[0]:"+args[0]);
System.out.println("args[1]:"+args[1]);
//args[0] = "-10" ---> -10 : Type conversion
int num = Integer.parseInt(args[0]);
///Integer.parseInt (char -> num)
System.out.println("Absolute Value:"+abs(num));
int num1 = Integer.parseInt(args[1]);
///Integer.parseInt (char -> num)
System.out.println("Absolute Value:"+abs(num1));
}
}
Array Copy
You can also copy the array that you already have, by using for loop.
public class ArrayEx08 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] oldArray = {10, 20, 30}; //Original array
int[] newArray = new int[5]; //New array
for(int i=0; i<oldArray.length; i++) {
newArray[i] = oldArray[i]; //for loop
}
for(int i : newArray) {
System.out.println(i+"\t");
}// Initial value : 0.0
}
}
What is Structured Query Language (SQL)? As a DB standard language (specified by ISO) with its syntax, most databases use SQL to query, enter, modify, and delete data.
Types of SQL
Data Definition Word (DDL): A database administrator or application programmer is stored in a data dictionary as the language for defining the logical structure of the database.
Data manipulation words (DML): As the language used to manipulate data stored in the database, perform data retrieval (Retrieval), addition (Insert), deletion, and update operations.
Data Control Language (DCL): Language used to manage transactions on database systems, such as granting access to data
SQL Statements
Type
Statement
Use
DQL(Data Query Language)
SELECT
To search the data
DML(Data Manipulation Language)
INSERT UPDATE DELETE
To change the data
DDL(Data Definition Language)
CREATE ALTER DROP RENAME TRUNCATE
To create and change objects
TCL(Transaction Control Language)
COMMIT ROLLBACK SAVEPOINT
To process transaction
DCL(Data Control Language)
GRANT REVOKE
To control the data
*CRUD
In computer programming, create, read, update, and delete(CRUD) are the four basic operations of persistent storage. They correspond to 'insert', 'select', 'update', and 'delete' in SQL so it is vital to remember the statements.
<DDL>
o Create a table
create table table-name (
column name data type,
Column name data type, ……….);
create table member01(
id varchar2(20),
name varchar2(20),
address varchar2(50),
phone varchar2(20));
o Table list output
select * from tab;
o Table structure output
describe member01;
o Rename the table
alter table old table name rename to new table name;
alter table member01 rename to member02;
The table name can also be changed.
rename member01 to member02;
o Add a new column to the table (add operator)
alter table member01 add (password varchar2(30));
o Modify the column of the table (modify operator)
alter table member01 modify (password varchar2(50) not null);
Other data types if the column already has data cannot be changed too.
o Delete columns in the table (drop operator)
alter table member01 drop column column_name;
alter table member01 drop column password;
o Delete Constraints
alter table member01 drop primary key;
o Deleting a table
drop table member01;
How do I delete this temporary table parmanently?
purge recyclebin;
How do I delete a table completely from scratch?
drop table member01 purge;
<DML>
1. INSERT(Data Input) Format: insert into tablename (column1, column2,...) values (data1, data2,...); insert into table name values (data1, data2,...);
insert into dept01(deptno, dname, loc)
values(10,'ACCOUNTING', 'NEW_YORK');
insert into dept01(dname, loc, deptno)
values('RESEARCH', 'DALLAS', 20);
insert into dept01 values(30, 'SALES', 'CHICAGO');
insert into dept01 values(40, 'OPERATIONS','BOSTON');
Following is an example of creating a row by using 'insert'. It has to be '' not "" when we insert the values. SQL is not sensitive with Uppercase/Lowercase, but it has to be distinguished in terms of values. As you see below, here are 2 ways to insert the values. Depending on the situation, one can be chosen.
2. UPDATE (Data Modification) Format: update table name set column 1 = Value to modify 1, Column 2 = Value to modify 2,... where conditional;
If you don't use 'where', the address of the whole table will be changed, so be careful!
After being updated, the address value of table 'test2' is changed.
3. DELETE (Data Deletion) format: delete from table name where conditional;
To delete it is relatively easy. After deleting from the table, you can see no rows selected.
In Java, two different length constructs have different roles.
".length", the length property is used with the String and Array class. It returns the number of characters in a text String or the size of an array. The length method, "length" with brackets"()", is for data encapsulation.
The biggest similarity between them is that they help to determine the number of elements an object contains. However, the method works with the String class, while the property works with arrays.
Here are some examples of them.
// length can be used for int[], double[], String[]
// to know the length of the arrays.
// length() can be used for String, StringBuilder, etc
// String class related Objects to know the length of the String
public class Test {
public static void main(String[] args)
{
// Here array is the array name of int type
int[] array = new int[4];
System.out.println(array.length); //4
// Here str is a string object
String str = "Meadow";
System.out.println(str.length()); //6
}
}
.length
public class Test {
public static void main(String[] args)
{
// Here str is the array name of String type.
String[] str = { "Java", "is", "easy", "and", "fun" }; //5
System.out.println(str.length);
}
}
length()
It will occur an error with this code.
public class Test {
public static void main(String[] args)
{
String[] str = { "Meadow", "Min", "Young" }; //error
System.out.println(str.length());
}
}
This file has to be in a package in the src folder.
package beans;
public class LoginBean {
// Fields to save the values that user inserted
private String userid;
private String passwd;
private String _userid;
private String _passwd;
//Initial ID and password
public LoginBean() {
_userid = "myuser";
_passwd = "1234";
}
// To check if the IDs and the passwords match
public boolean checkUser() {
if(userid.equals(_userid) && passwd.equals(_passwd))
return true;
else
return false;
}
public void setUserid(String userid) {
this.userid = userid;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getUserid() {
return userid;
}
public String getPasswd() {
return passwd;
}
}
login.jsp
<%@ page contentType="text/html;charset=euc-kr"%>
<jsp:useBean id="login" class="beans.LoginBean" />
<jsp:setProperty name="login" property="*" />
<HTML>
<HEAD>
<TITLE>Log in Example</TITLE>
</HEAD>
<BODY>
<center>
<H2>Log in Example</H2>
<HR>
<%
if (!login.checkUser()) {
out.println("Failed to log in.");
} else {
out.println("Successfully logged in.");
}
%>
<HR>
User ID :
<jsp:getProperty name="login" property="userid" /><BR>
User password :
<jsp:getProperty name="login" property="passwd" />
</BODY>
</HTML>
The new version of Oracle takes up a lot of memory and RAM, so I downloaded the XE11 version. OracleXETNSListener and OracleServiceXE have to be constantly running on your computer, so once you download the app, you will find that turning on/off takes more time. Therefore, when you don't use it, you would better set the Startup type "Manual" instead of "Automatic."
Connecting to Client
Open the command prompt and enter 'sqlplus name of the account/password. to show the user's name, enter 'show user'.
You could also enter 'sqlplus,' and the prompt will ask for your user name and password.
To change the account, you could use 'connect account name/password as sysdba'
To be safe from the mistakes you will make with the system account, Oracle offers an account named 'scott' for demonstration purposes. According to legend, this account was named after Bruce Scott, co-author and co-architect of Oracle v1 to v3, and the password was the name of his daughter's cat, Tiger. (What a monument!)
To set your account's password, you can use 'alter user account name identified by password'. To see the list of the table, insert 'select*from tab;' and you will see 4 tables on the list.
To exit, you can either insert 'exit' or 'quit', and you will see this :
*When you forget the password of DBA and USER
It is impossible to know your previous password but you can reset your password. Enter 'sqlplus /"as sysdba"' and check 'show user' first, and enter 'alter user ID identified by yournewpassword;'
It would help if you had some place to store your data on any website or webpage. Even if you made a perfect website with JSP, unless you connect it to DB, it wouldn't have any function to store the users' information. So, It is essential to know how to connect the two sources.
There are three significant ways to connect JSP and Oracle: JDBC(Java DataBase Connectivity), DBCP(DataBase Connection Pool), and ORM(Object Relational Mapping) framework. iBatis, MyBatis, hibernate, and JPA are ORM frameworks. Among them, we will discuss JDBC first.
JDBC
JDBC Configuration
To connect to Oracle, you first need a JDBC Driver. Depending on the version set on your PC, I will download an ojdbc6.jar.
After then, we will test if the connection is successfully run or not. Oracle Smith account must be connected if you want to connect them successfully.
Now, to run the Oracle in Eclipse, we will make a folder named "sql" in the webcontent folder and create a new SQL file.
Open the Data Source Explorer and connect the Scott account to run the codes.
Now, let us look at the overall procedure of connecting the database to JSP.
1. Load JDBC Driver
Create a class.forName()
2. Connect Database
java.sql.Connection
3. Create SQLs
java.sql.Statement
java.sql.PreparedStatement - The most used
java.sql.CallableStatement
4. Send SQLs
executeQuery()
executeUpdate()
5. Receive result
java.sql.ResultSet
6. Disconnect
Connection.close()
To start connecting, we need first to create a table.
create table member1(
id varchar2(12) primary key,
passwd varchar2(12) not null,
name varchar2(10) not null,
reg_date timestamp not null );
select * from tab;
select * from member1;
Before, let us look at the JSP Model1 architecture.
We already made a DTO class in Java, and that is JavaBean.
JavaBean is a component written in Java.
There are some things that you need to consider when you make a Javabean.
1. In JavaBean, the member variable is called property. 2. Property is a field for storing values created by declaring the access controller private. 3. Properties are used as intermediate data storage when the contents of the JSP page are stored in the DB or when the contents stored in the DB are printed on the JSP page. 4. set() method and get() method are used a lot in JavaBean, and they mainly use public access modifiers. 5. The Java Bean file's storage location should be in the WEB-INF/classes folder.
We will make a java file called "SimpleBean.java" in the src folder.
You can easily write generate getters and setters by right-clicking the mouse.
SimpleBean.java
// JavaBean, DTO Class(Data Transfer Object)
package javaBean;
public class SimpleBean {
private String msg; // Property
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Create a table first to store data in Oracle or Eclipse.
myoracle.sql
select * from tab;
select * from member1;
create table member1(
id varchar2(12) primary key,
passwd varchar2(12) not null,
name varchar2(10) not null,
reg_date timestamp not null );
insertTestForm.jsp
<%@ page contentType="text/html; charset=euc-kr"%>
<html>
<head>
<title>Insert record</title>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(document).ready(function() {
$("form").submit(function() {
if ($("#id").val() == "") {
alert("Insert your ID.");
$("#id").focus();
return false;
}
if ($("#passwd").val() == "") {
alert("Insert your password.");
$("#passwd").focus();
return false;
}
if ($("#name").val() == "") {
alert("Insert your name.");
$("#name").focus();
return false;
}
});
});
</script>
</head>
<body>
<h2>Insert record on member1 table</h2>
<FORM METHOD="post" ACTION="insertTest.jsp">
ID : <INPUT TYPE="text" NAME="id" id="id">
<p>
Password : <INPUT TYPE="password" NAME="passwd" id="passwd">
<p>
Name :<INPUT TYPE="text" NAME="name" id="name">
<p>
<INPUT TYPE="submit" VALUE="Submit">
</FORM>
</body>
</html>