Anda di halaman 1dari 32

AMA Computer College Tarlac Zamora St.

San Roque, Tarlac City, Tarlac


Ian Carlo M. Serrano Jervin Christian L. Kabigting Jonel Christian P. Ramilo

March 26, 2012


CSCI0209: Computer Programming I.

Java is a programming language originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java is currently one of the most popular programming languages in use, particularly for client-server web applications, with a reported 10 million users. James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. They are the founders of Java.

High Level Language Low Level Language Machine and Assembly Language BYTECODE Java Virtual machine
CSCI0209: Computer Programming I.

High Level Programming Language - programming language with strong abstraction from the details of the computer. In comparison to low-level programming languages, it may use natural language elements, be easier to use, or be from the specification of the program, making the process of developing a program simpler and more understandable with respect to a low-level language. The amount of abstraction provided defines how "highlevel" a programming language is. Low Level Programming Language provides little or no abstraction from a programming language that computer's instruction set

architecture. The word "low" refers to the small or nonexistent amount of abstraction between the language and machine language; because of this, low-level languages are sometimes described as being "close to the hardware." Compiler converts high level language to low level language. Machine Language Most basic level of programming languages. Uses binary coded instruction. It does not need a compiler. Assembly Language They are sometimes called symbolic languages, because symbols are used to represent operation codes and storage locations. It does need a simple compiler. Byte Code a machine language to any particular computer. Java Virtual Machine - a virtual machine capable of executing Java bytecode. Oak old name of java.
CSCI0209: Computer Programming I.

How to Compile and Run 1. Create a source file contains code, written in the Java programming language, using any text editor. Sample code:

2. Save it as and save it to <directory when you install your JDK>\Java\jdk<version of your JDK>\bin

In my case, Ive installed JDK to C:\Java\jdk1.7.0_02\

CSCI0209: Computer Programming I.

3. Open command prompt and change your current directory to the directory where your file is located.

4. Now











javac and diagnose any errors appeared.

5. In the same directory, enter the java HelloWorld at the prompt to run your program.

Congratulations! Your program works!

CSCI0209: Computer Programming I.

Sample Program A

Source Code:
class Printest { public static void main(String[]args) { int i,j; i=7; j=4; System.out.println("i="+i); System.out.println("i+j="+ i+j); System.out.println("i+j="+(i+j)); System.out.print("The sum of "+i+" and "+j+" is "+(i+j)+"."); } }


CSCI0209: Computer Programming I.


CSCI0209: Computer Programming I.

Program is a set of detailed instructions to instruct the compiler to perform a task. Source Code is the line of instructions. Block Comment begins with forward slash / followed by an asterisk * and ends with symbol reversed /* This is a block comment */

Line Comment is a comment that spans only a single line or part of line. //Comment Access Modifier specified the circumstances in which the class can be accessed. Java Class Naming Rules: 1. Must begin with a letter, an underscore or a dollar sign. 2. May contain only letters, digits, underscore or a dollar sign. 3. May not use reserved words. Compiler is a programming language tool that translates source code to executable code that closer to machine language. Byte Code is the code that can be interpreted on any machine. Javac is the command used to compile java source code into byte code. Debugging is the process of fixing errors. Syntax errors usually are typographical errors. Semantic errors is the one dealing with the meaning of the code. Run-Time errors is an error which will not display until you run or execute the program.
CSCI0209: Computer Programming I.

Java Escape Codes are non-printing control codes. Code \t \b \n Concept Horizontal tab Backspace New line Result Moves insertion point 8 spaces to the right. Moves insertion point one space to the left. Moves insertion point down one line and to the left margins. Importing Packages Packages are collections of classes which contain portable java byte-code. JDK Provided Packages Package Name Java.applet Java.awt Java.lang Java.util Description Classes to facilitate using applet. Classes to facilitate graphics user interfaces (GUI). Classes to facilitate input and output. Classes to facilitate data types, threads, string etc. Classes used for dates, vectors and others. Used for networking
CSCI0209: Computer Programming I.

.awt means abstract window toolkit. Data are small pieces of unprocessed information such as word text, or numbers that a computer program uses in order to perform operations and produced output.

Primitive data types are data types that are structured by java to hold simple kind of data.

1 0

Java Primitive Data Types Type Boolean Byte Char/string Double Float Int Short long Description - stores data in only one of two stats. - stores whole number values in 8bit signed locations from -128 to +128. - stores any one of the 65436 single characters of Unicode set. - stores number with up to 14 or 15 decimal places as double precision. - stores number up to 6 or 7 decimal places as floating point values. - stores whole number values 32bit signed location. - 2 bytes, signed (two's complement), -32,768 to 32,767 - 8 bytes signed (two's complement). Ranges from
-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

Identifier is the word that the programmer chooses to label a storage address in memory. Variable is a storage location for data that may change during processing of the computer program. Constant is a value that does not change during the course of the program.
CSCI0209: Computer Programming I.

Assignment statement is a line of code beginning with a location, followed by an equal sign (=) and the new value. Location = value; / num1 = 50;

1 1

Arithmetic Operations (+) Addition (-) Subtraction (*) Multiplication (/) Division (%) Modular Division

Comparison Operator (<) Less than (>) Greater than (<=) Less than or equal (>=) Greater than or equal (==) equal to (!=) not equal to

Concatenation is the way to combine strings and variable on the same line. System.out.print(The Answer is ); System.out.print(answer); is the same as: System.out.print(The Answer is + answer); User Input Stream data flowing in and out of a program. Class System.out Function -accepts data from the keyboard buffer wrapped in the InputStreamReader (ISR).
CSCI0209: Computer Programming I.

-send output to the display or redirect to a designated file.

Buffer is a data area shared by a hardware device on programs, where data area held until they are needed by the processor. Concatenator is the symbol (+) used to combine a string or a variable.

Logical Operators && || ! And Or Not

1 2

Sample Program B Source code:

import*; public class Exer { public static void main(String[]args) throws IOException { BufferedReader dataIn = new BufferedReader(new InputStreamReader(; String name; String add; int age; String strage; System.out.print("Name: "); name=dataIn.readLine(); System.out.print("Address: "); add=dataIn.readLine(); System.out.print("Age: "); strage=dataIn.readLine(); age=Integer.parseInt(strage); System.out.println("Hello "+name+ " your location is "+add); } }


CSCI0209: Computer Programming I.

1 3

Sample Program C

Source code:
import*; public class Act { public static void main(String[]args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(; String sq1, sq2, scs, spex; Double pq1, pq2, pcs, pex, pgrade; System.out.print("\n\n"); System.out.print("\t \t COLLEGE INFORMATION SYSTEM"); System.out.println("\n"); System.out.print("Enter quiz 1: "); sq1=br.readLine(); System.out.print("Enter quiz 2: "); sq2=br.readLine(); System.out.print("Enter class standing: "); scs=br.readLine(); System.out.print("Enter Prelim Exam: "); spex=br.readLine(); pq1= Double.parseDouble(sq1); pq2= Double.parseDouble(sq2); pcs= Double.parseDouble(scs); pex= Double.parseDouble(spex); pgrade=((pq1*.2)+(pq2*.2)+(pcs*.1)+(pex*.5)); System.out.println("Your Prelim Grade is: "+pgrade); if(pgrade>=75) { System.out.print("Passed"); } else { System.out.print("Failed"); } } }

CSCI0209: Computer Programming I.

1 4


1 5

CSCI0209: Computer Programming I.


1 6

CSCI0209: Computer Programming I.

JOptionPane is a part of java swing library and used to input number or string. Swing is used to create a program with graphical user interface (GUI). Package:

import javax.swing.*;

Two Methods Input

input=JOptionPane.showInputDialog(null, "Input Here:");

Output JOptionPane.showMessageDialog(null, "This is an Output");

CSCI0209: Computer Programming I.

1 7

Sample Program D

Source code:
import*; import javax.swing.*; public class Pane { public static void main(String[]args) { String name; int ID, num2, num1, sum; name=JOptionPane.showInputDialog(null, "Student Name:"); ID=Integer.parseInt(JOptionPane.showInputDialog (null,"Student ID:")); num1=Integer.parseInt(JOptionPane.showInputDialog (null,"First number:")); num2=Integer.parseInt(JOptionPane.showInputDialog (null,"Second Number:")); sum=num1+num2; JOptionPane.showMessageDialog(null, "The sum is "+sum); System.out.println("Hello "+name); System.out.println("Student ID: "+ID); } }

CSCI0209: Computer Programming I.


1 8

1 9

CSCI0209: Computer Programming I.

Control flow Statement breaks up the flow of execution by the employing decision making, looping, branching and thus enable your program to conditionally execute a particular blocks of code.

If-else Statement enables your program to selectively execute other statement based on some criteria. Syntax: if (expression) { Statements(s); } else { Statements(s); }

Switch Statement it can have a statement and numbers of possible execution paths. Syntax: switch (variable) { case 1: Statement 1; break;

case 2: Statement 2; break;

default; Statement; break; }

CSCI0209: Computer Programming I.

2 0

Sample Program E Source code:

public class IfElse { public static void main(String[]args) { int testscore; char grade;
testscore=76; if (testscore >= 90) { grade = 'A'; } else if (testscore >= grade = 'B'; } else if (testscore >= grade = 'C'; } else if (testscore >= grade = 'D'; } else { grade = 'F'; } System.out.println("Grade } } CSCI0209: Computer Programming I.

80) {

70) {

60) {

= " + grade);


2 1

Sample Program F Source code:

public class SwitchSt { public static void main(String[]args) { char grade; grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : System.out.println("Very Good!"); break; case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); break; case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } } }


CSCI0209: Computer Programming I.

2 2


2 3

CSCI0209: Computer Programming I.

Looping For loop provides a compact way to iterate over a range of values. Syntax: for(initialization; Boolean_expression; update) { //Statements }

Here is the flow of control in a for loop: 1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. 2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop. 3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. It can also be an increment or decrement. This statement can be left blank, as long as a semicolon appears after the Boolean expression. 4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the for loop terminates.

Nested for loop The placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop. While all types of loops may be nested, the most commonly nested loops are for loops.

CSCI0209: Computer Programming I.

2 4

Sample Program G Source code:

public class LoopA { public static void main (String[]args) { int i; for(i=1; i<=5; i++) { System.out.print(i); } }


Sample Program H Source code:

public class LoopB { public static void main (String[]args) { int i; for(i=1; i<=5; i++) { System.out.println(i); } }


CSCI0209: Computer Programming I.

2 5

Sample Program I Source code:

public class LoopC { public static void main (String[]args) { char i; int j; for(i='A'; i<='Z'; i++) { System.out.print(i); } System.out.println(); for(j=1; j<=6; j++) { System.out.println("*"); } } }


CSCI0209: Computer Programming I.

2 6

Sample Program J Source code:

public class LoopD { public static void main (String[]args) { int k,i; for(k=1; k<=15; k++) { for (i=1; i<=k; i++) { System.out.print("*"); } System.out.println(); } } }


CSCI0209: Computer Programming I.

2 7

Sample Program K Source code:

public class LoopE { public static void main (String[]args) { int k,i; for(k=1; k<=15; k++) { for (i=15; i>=k; i--) { System.out.print(" "); } for (i=1; i<=k; i++) { System.out.print("*"); }

System.out.println(); }
} }


CSCI0209: Computer Programming I.

2 8

Sample Program L Source code:

public class LoopF { public static void main(String[]args) { int i,k; for(k=1; k<=10; k++) //First triangle { for (i=40; i>=k; i--) { System.out.print(" "); for (i=1; i<=k; i++) { System.out.print("**"); System.out.print("\n"); } for(k=5; k<=15; k++) //Second Triangle { for (i=40; i>=k; i--) { System.out.print(" "); }

for (i=1; i<=k; i++) { System.out.print("**");

System.out.print("\n"); } for(k=10; k<=20; k++) //Third Triangle { for (i=40; i>=k; i--) { System.out.print(" "); for (i=1; i<=k; i++) { System.out.print("**"); } System.out.print("\n"); }

} CSCI0209: Computer Programming I.

2 9

for(k=1; k<=10; k++) //Rectange { for (i=1; i<=38; i++) { System.out.print(" "); for (i=1; i<=6; i++) { System.out.print("*"); System.out.print("\n"); } } }


CSCI0209: Computer Programming I.

3 0

The while and do-while Statements

The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as: while (expression) { statement(s) } The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the whilestatement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program: class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } }
CSCI0209: Computer Programming I.

3 1

You can implement an infinite loop using the while statement as follows: while (true){ // your code goes here } The Java programming language also provides a do-while statement, which can be expressed as follows: do { statement(s) } while (expression);

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program: class DoWhileDemo { public static void main(String[] args) { int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); } }
CSCI0209: Computer Programming I.

3 2