You are on page 1of 5

CMSC 22: Object-Oriented Programming (Laboratory)

Institute of Computer Science


College of Arts and Sciences, UPLB
2​nd​ Semester, SY 2018-19

LAB HANDOUT 01: Java Basics I


--------------------------------------------------------------------------------------------------------------------------------------
OBJECTIVES: No. of points: Discussion/drills(5) + Exercise(10)

At the end of the session, students should be able to:


● Write, compile and run a simple Java program
● Import dependencies
● Appropriately use different primitive data types
● Use variables, literals, and operators in expressions and statements
--------------------------------------------------------------------------------------------------------------------------------------

What is the version of Java in your machine?


Open a terminal window from your linux machine and type:
icsuser@pclab9$ java -version

Your first java program


● Launch the ‘Sublime Text’ application (i.e. the text editor that you will use for this course)
● Type in the documentation text of your first java program:
/***********************************************************
* This is a simple program that prints “Hello World”.
*
* @author <your name>
* @created_date 2017-01-17 11:42 ​==> use military time format e.g. 10 pm is 22:00
*
***********************************************************/
● Type the rest of the code and save it as ​HelloWorld.java​:

class HelloWorld {
public static void main(String[] args){
System.out.println("Hello World!!!");
}
}

Remember the syntax:

class ​CLASSNAME​ {
public static void main​(String[] args){
STATEMENTS
}
}

● Your directory structure:


/home/icsuser
|--Desktop
|--|--HelloWorld.java
● Take note of the following:
○ Camel-case notation for naming files and classes, first letter of “HelloWorld” is upper-case
○ Proper indentation
○ Java is case-sensitive
● On the terminal window, type the following:
icsuser@pclab9$ cd ~
icsuser@pclab9$ cd Desktop
icsuser@pclab9:~/Desktop$ pwd ==> prints ‘working directory’
icsuser@pclab9:~/Desktop$ ls ==> lists all contents of the current directory
icsuser@pclab9:~/Desktop$ cd .. ==> moves to up the parent directory
● See if your Java file is in there

What are java “Source files”


● These files end with the ​.java​ extension
Ex. ​Student.java, Course.java, World.java
● If public class is present, the class name should match the unextended filename​, ​e.g., a public class named
Student​ should be saved as ​Student​.​java
● Three top-level elements​ that may appear in a Java file. If they are present, then they must appear in the
following order:
1. package declaration
2. import statements
3. class definitions
Example:
package uplb; //package declaration

import java.util.Scanner; //import statements


import java.io.*;

class Student { ... } //class definition

● Compile and run the code (make sure you are inside the directory where your Java file is)
icsuser@pclab9:~/Desktop/cmsc22-wk01$ javac -d . HelloWorld.java
icsuser@pclab9:~/Desktop/cmsc22-wk01$ java HelloWorld

The Java Compiler and Java Virtual Machine

The Java Compiler and Java Virtual Machine1

Without package With package

Compile: generates class files javac -d <directory> <filename>.java


Ex.​ javac -d . MyFirstClass.java

Run: executes the program java <Class name> java <package name>.<Class name>
Ex.​ java MyFirstclass Ex.​ java myfirstpackage.MyFirstClass

Notes:
● Class files will be produced corresponding to the classes in your Java files.
● <directory> refers to the directory where the class files will be generated.
● In case a lot of Java files needs to be compiled, the wildcard character “*” can be used to compile all java files
​ avac -d . *.java
in the current directory:​ j

1
​Source: http://i.imgur.com/KhUw309.png
● When running a Java Class, make sure you are ​outside​ the folder of your file’s package if any.
● “​.”​ ​refers to the current directory. Only classes with the ​main() ​method can be ran. See The ​main()​ method
=========================================================================================
Note: In your exercises, submit all .java files
(not just the .class files!!!)
=========================================================================================

Try this! From Sublime Text, create a new file and complete the code below

package myfirstpackage;

class MyFirstClass {
public static void main(String[] args){
___________________________________ // prints “My first java class!”
}
}
Save as ​MyFirstClass.java​, compile and run.

The ​main()​ Method


The entry point for Java applications
To create an application, write a class definition that includes a​ main()​ method

The method signature of ​main()​:


public static void main(String[] args)

Class Files
Recompiling overwrites the previous class files. There is no need to be afraid of removing files from previous
compilations. ​You may delete them but make sure you have the original (.java) source files!

Literal
A value specified in the program source. This may appear on the right side of assignments and in method
calls. You cannot assign a value into a literal, so they cannot appear on the left side of an assignment.

Boolean Literals
The only valid literals of ​boolean ​type are ​true ​and ​false​.

Character Literals
A ​char ​literal can be expressed by enclosing the desired character in single quotes.
Examples:
'w' // the character literal w
'_' // the character literal underscore
'*' // the character literal asterisk

Integral Literals
Integral literals may be expressed in decimal, octal, or hexadecimal. The default is decimal.
Examples: 18 0 1000

Floating-point Literals
A floating-point literal expresses a floating-point number. In order to be interpreted as a floating-point
literal, a numerical expression must contain one of the following:
○ A decimal point: ​1.414
○ The suffix ​F ​or ​f​, indicating a ​float ​literal: ​1.828f
○ The suffix ​D ​or ​d​, indicating a ​double ​literal: ​1234d
○ The letter ​E ​or ​e​, indicating scientific notation: ​4.23E+21

​ o
Note: A floating-point literal without F ​ r ​D ​suffix defaults to d
​ ouble ​type.
Variables
Variables in Java must begin with a letter, a dollar sign($), or an underscore(_); subsequent characters may
be letters, dollar signs, underscores, or digits.

Legal Illegal
lecturer 3_yearLevel
NSTPCourse !sophomore
$tuitionFee

A variables should be declared first before it can be used in your program. It should be declared once as any
of the following ​primitive data types​:

Data Type Size(Bits) Data Type Size(Bits)


boolean 1 char 16
byte 8 short 16
int 32 long 64
float 32 double 64
*Java is a ​Hybrid OOPL​. It has both primitive and object data types. We’ll discuss object types later on.

Syntax:
dataType varName;
int units;
boolean quotaCourse;

Assignment Operators
Assignment operators set the value of a variable or expression to a new value. Simple assignment uses =.
int age = 5;
double pi = 3.1415;
char x = 3.5; // ERROR!

Operators such as ​+= and ​*= provide compound “calculate and assign” functions. These compound operators
take a general form ​op=​, where op can be any of the binary non-boolean operators already discussed. In
general, for any compatible expressions x and y, the expression ​x op= y​ is a shorthand for ​x = x op y​.
x += 3; // equivalent to x = x + 3;
y -= 1; // equivalent to y = y - 1;

Arithmetic Operators
The operators * and / perform multiplication and division on all numeric types and char.
Dividing an integer with another integer will result to an integer and, typically, a lot of information will be lost.
2 * 50
16.5 / 5

Modulo operator returns the remainder of dividing the two operands.


17 % 5
-5 % 2

The operators + and – perform addition and subtraction. They apply to operands of numeric type but,
uniquely, + is also permitted where either operand is a String object.
1 + 1
2 – 1
"​key" + "board" -> "keyboard"

Constants
● Constants can be declared using the ​final ​keyword. A convention in Java is to capitalize all the characters
of a constant identifier.
final int NO_OF_SUBJECTS = 6;
final double MINIMUM_WAGE = 300.58D;

Java Reserved Words and Operators: ​See separate document - “Handout (Additional Reference) 01”
Basic Output
A typical way to write a line of output data is:
System.out.println(data);

Try this:
package myfirstpackage;

class MyFirstClass {
public static void main(String []args){
// . . .
_____________________ // declare awesomeness as 10
System.out.println("Welcome to Java programming!");
System.out.println("Awesomeness is " + awesomeness);
}
}
Update your ​MyFirstClass.java

The ​Scanner ​methods


Scanner ​class has some methods used for getting inputs from the user. This is somewhat equivalent to
scanf()​ function in C.
Method Usage
next() Scans the next token of input before a space as a String
nextLine() Scans the next line of input including spaces as a String
nextInt() Scans the next token of the input as an int type
nextFloat() Scans the next token of the input as a float type
nextDouble() Scans the next token of the input as a double type

Try this:
package myfirstpackage;

import java.util.Scanner;

class MyFirstClass {
public static void main(String[] args){
//...
int myInt;
String name;
Scanner sc = new Scanner(System.in);

System.out.println("Enter your name:");


name = sc.next();

System.out.println("Hello "+ name + "!");

System.out.println("Enter an integer value:");


myInt = sc.nextInt();

__________________________ // displays the value of myInt


}
}
Update your ​MyFirstClass.java

You might also like