Basic Overview of Java
CCPROG3 – AY2223T3 – ETighe
Outline
• Brief overview of Java
• Structure of a Java program
• Running through basic programming concepts
• Compiling a Java program
• Looking at API
We will be working with Java in the terminal. Please expect to
code through the session. J
How many where able to
build and run a “Hello World”
program in Java?
Please raise your
hand if you have J
Image source: https://www.kindpng.com/imgv/oRomoh_raised-hands-png-transparent-hand-emoji-png-download/
Java
• Is an object-oriented language
• Object-oriented implies the support of most, if not all,
concepts that make up an OO environment
• Object-based usually refers to the support of the creation of
objects but that there’s a lack of higher OO concepts, such
as inheritance or polymorphism (more on these after the midterm!)
• Is both a compiled and interpreted language
• What does this mean?
Compiled Language
Source High Level Programming Language
Code e.g. C, Java
A software program that translates
Compiler high level language program into an
executable machine language program.
Executable May be executed many times but on
one type of computer only
File
Interpreted Language
Source
Code
High Level Language Fetch
(Statement)
e.g. Python
Execute Interpret
Interpreter
Translates and
executes one
instruction at a
time
Java
For example:
MyApp.java Java Source Code
Compiler (javac command)
MyApp.class
Java bytecode: machine language of a “virtual” machine
Java Virtual Machine
Java bytecode Interpreter (java command)
Commands specific
for your OS Mac OS Windows Linux
Operating System
Writing Java Applications
public class MyApp { • A Java application consists of
one or more Java classes
• Class declaration for each class:
} • Access modifier (public, private)
• Class name
Filename: MyApp.java • Should start with an Uppercase Letter
• File Extension: .java • CamelCased
• File Name: Class Name
(exact case & spelling) • Braces mark the start and end of
the class declaration
Don’t worry so much about Access Modifiers for
now. We’ll discuss more of this in time. J
Why have Class names in upper case?
• You don’t have to… but it isn’t good practice
• Coding standards to follow…
• Classes start with an uppercase
• Methods and variables should start with a lowercase
• Apply snake case for constants (in all uppercase) and
camel case for everything else
Class Declaration
• Can have at most one main() method, whose
signature is:
public static void main (String[] args)
• The runtime system calls the class’s main() method.
public class MyApp {
public static void main(String[] args) {
}
}
Java language is strongly-typed
• The type of every variable and expression must be
known at compile time
• Primitive Types (boolean, char, int, long, float, double)
• Reference Types (String, JFrame, user-defined types)
• Indicating the data type of the variable…
• Limits the type of data and the values that the variable can
hold
• Limits the result of an expression
Declaring Variables
• Variables can be declared throughout the code, but
they must be declared before first use
• Name the variable
• Data type of the variable
• All variable declarations must be within the class or
method
Declaring Variables (in methods)
We will expand on the syntax when we start
Syntax looking at classes and objects
<dtype> <var1>;
<dtype> <var1>, <var2>;
<dtype> <var1> = <value>;
Example
int nVal; // nVal stores an integer value.
double dGrade; // dGrade is a real number.
char cAnswer, cType;
boolean bStop = false;
Output Statement
• To display text on a terminal/console, use
• System.out.print() à prints text from wherever the cursor is currently at
• System.out.println() à prints text like print() and adds a new line character at the end
• Take note: Case sensitive!
But wait… what is System? Why is there an out?
Answer: Consult the API!
https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/System.html
Output Statement
• To display text on a terminal/console, use
• System.out.print()
• System.out.println()
• Take note: Case sensitive!
• Parameters placed inside the parenthesis are the
values to be displayed on screen
• Parameters may be any expression that would evaluate
into a literal
Let’s trace code…
Statements
System.out.print("hi");
System.out.print(35);
int nVal = 15;
System.out.print(nVal);
System.out.print(nVal * 3);
Screen output
hi351545
Let’s trace code…
Statements
System.out.println("hi");
System.out.print(35);
int nVal = 15;
System.out.println(nVal);
System.out.print(nVal * 3);
Screen output
hi
3515
45
Let’s trace code…
Statements
System.out.println("hi\n");
System.out.print("Let’s see\n\nOk?");
Screen output
hi
Let’s see
Ok?
Example Make sure the filename is the name
of the class in exact casing
public class MyApp { To compile
public static void main (String[] args) { javac <filename>.java
double dArea = 0.0; java <filename>
double dRadius;
dRadius = 5;
dArea = 2 * 3.16 * dRadius * dRadius; Example
javac MyApp.java
System.out.println("Area is " + dArea); java MyApp
}
} Yes… this will work
Produces a
Let’s compile and run this program! J Looks for a .class
.class file in
your
file of the specified
current
file name and runs
directory
the program
How was that?
Any issues or problems?
Getting input via the terminal
• It’s not as straight forward as in C or Python…
• We must use a Scanner object to help us get input
• Things we need to do:
1. Import the Scanner class so our file has access to it
2. Declare a Scanner variable
3. Instantiate a Scanner object passing the InputStream
4. Use the Scanner object to get input
5. Close the Scanner’s input stream
Importing…
• The Java API is an extensive library… so much that it
isn’t good to have everything accessible right away
• Importing everything from multiple libraries might lead to
conflicting imports
• Regardless, we’ll need to import classes that are useful
in helping us solve problems
Importing… Scanner
OR java.util.*; which imports all classes under java.util
import java.util.Scanner;
API of Scanner:
public class MyApp { https://docs.oracle.com/en/java
public static void main (String[] args) { /javase/12/docs/api/java.base/
double dArea = 0.0; java/util/class-
use/Scanner.html
double dRadius;
dRadius = 5;
dArea = 2 * 3.16 * dRadius * dRadius;
System.out.println("Area is " + dArea);
}
}
Declaring a Scanner Object…
import java.util.Scanner; Scanner
• Is a reference data type
public class MyApp { • Reference data types need
public static void main (String[] args) { to be instantiated before use
Scanner sc; • I.e. we need to create an
instance of a class
double dArea = 0.0; • Needs some input stream
double dRadius; which can be…
• From the terminal
dRadius = 5; • From a file
dArea = 2 * 3.16 * dRadius * dRadius;
System.out.println("Area is " + dArea);
}
}
Instantiating a Scanner object…
import java.util.Scanner; Scanner
• As we just want to get input
public class MyApp { from the terminal, we can
public static void main (String[] args) { use the InputStream of
Scanner sc = new Scanner(System.in); System and pass that in as
a parameter
double dArea = 0.0;
double dRadius; This is a form of abstract in code
as we can somewhat understand
dRadius = 5; that Scanner does something with
dArea = 2 * 3.16 * dRadius * dRadius; the input stream, but we don’t
see the code
System.out.println("Area is " + dArea);
}
}
Getting input…
import java.util.Scanner; Scanner
• As we just want to get input
public class MyApp { from the terminal, we can
public static void main (String[] args) { use the InputStream of
Scanner sc = new Scanner(System.in); System and pass that in as
a parameter
double dArea = 0.0; • nextDouble() returns a
double dRadius; double value that was input
by the user
dRadius = sc.nextDouble(); • Check the API for other
dArea = 2 * 3.16 * dRadius * dRadius; Scanner methods
System.out.println("Area is " + dArea); In our modification here, we
} assume the radius is unknown and
} that the user should give it as an
input.
Closing the Scanner’s input stream…
import java.util.Scanner; Good Coding Practice
• When done with an
public class MyApp { InputStream, close it to
public static void main (String[] args) { avoid a resource leak
Scanner sc = new Scanner(System.in);
• If you still plan to use it,
double dArea = 0.0; there’s no need to close it
double dRadius; • Just don’t forget to close it
once you’re done
dRadius = sc.nextDouble();
dArea = 2 * 3.16 * dRadius * dRadius; • Although… if you do forget
to close it, the JVM will
System.out.println("Area is " + dArea); eventually collect it. It is just
good to practice closing
sc.close();
} your streams because
} InputStream can come from
different places.
Comments in Java
• Internal documentation
// line comment • Notes within your Java code
• Types of Comments
/* multi-line • Line Comment
comment */ • Starts with //
• Texts in the same line after // will be disregarded by the
compiler
/** javadoc • Multi-line Comment
• Enclosed within /* and */
comment • Texts within the markers are disregarded
*/
• Javadoc Comment
Javadoc is going to be
• Enclosed within /** and */
important to understand so
• How to write javadoc comments: you can generate your own
https://www.oracle.com/ph/technical- system’s documentation
resources/articles/java/javadoc-tool.html
Example
/** This is my first Java application!
* @author Ed
*/
public class MyApp {
public static void main (String[] args) {
/* Multi-line
* Comment
*/
// Single-line comment
}
}
You’ll need to get use to
reading Java’s API
Documentation
API Documentation
package
API Documentation
Earliest JDK version
API Documentation
System.in
API Documentation
Return type Method
import java.util.*;
public class ScannerTest {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print (“How old are you? ”);
int nAge = sc.nextInt ();
int nYrOfBirth = 2019 - nAge;
System.out.println (“Approx. year of birth: ” +
nYrOfBirth);
sc.close ();
}
}
Questions so far?
Question
How does Java provide an
environment for object-
oriented programming?
Summary
• Java provides developers with an object-oriented
environment
• Forces you to think of a solution that makes use of objects
• A Java application can have one or more classes
• Running a Java app implies running the main() method
• Many programming constructs are the same with C,
but there are some difference
Summary
• Documentation is an important skill to develop
• Forces you to explain your code
• Helps others understand your code
• There are a lot of classes that are part of the Java API
• Some are immediately accessible, while others are not
• Get use to consulting API/documentation
Looking forward to our next session, we will…
• Practice on a couple of problems while working with
Java
• Usage of methods
• Strings
• Have a graded exercise
-fin-