0% found this document useful (0 votes)
9 views

Java101

The document provides an overview of Java technology, including its history, programming language features, and development tools like Eclipse and JDK. It covers essential concepts such as Java packages, access modifiers, coding standards, and exceptions, while also comparing Java with C#. Additionally, it discusses advanced topics like Javadoc, unit testing with JUnit, and GUI development using Java Swing.

Uploaded by

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

Java101

The document provides an overview of Java technology, including its history, programming language features, and development tools like Eclipse and JDK. It covers essential concepts such as Java packages, access modifiers, coding standards, and exceptions, while also comparing Java with C#. Additionally, it discusses advanced topics like Javadoc, unit testing with JUnit, and GUI development using Java Swing.

Uploaded by

kapilbaath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Java Basics

CPRG304 – Object-Oriented
Programming III

Kitty Wong © 2023


The Java Technology
• Created by James Gosling in 1996
• Graduate of the University of Calgary!

• Not just a programming language!


• Virtual machine specification that allows cross-platform
functionality (portability)
• “Write once, run anywhere”
The Java Programming Language
• High-level, class-based, OOP
• Very similar to C/C++/C#
• Still one of the most popular/used languages
• Especially for client-server web applications

• Various editions
• Java SE
• Java EE
• Java ME
• Java Card
Eclipse and the JDK
• Dedicated IDE mostly for Java, written in Java
• Free and open-sourced
• Rapid release cycles of 4 months
• https://www.eclipse.org/downloads/packages/
• Do NOT download the latest release! (unless your intention is to test
that release)
• Newest releases of anything == full of bugs!

• Java Development Kit (JDK) != JRE


• Java Runtime Environment == JVM
• Both JDK and JRE comes with Eclipse*
Eclipse Workspace
• Group of related projects
• Configurations global to all projects
• Eclipse settings global to all projects

• A directory (folder) that contains


everything relevant to what you’re
working on
• E.g. a workspace of all your code for this
course, and another for your personal
projects
Import demo00-Hello Kitty Project
• Import into Eclipse as an existing project:
“Hello Kitty!”
• Navigate to the folder where you have downloaded and
unzipped the sample project

• Now you should have this:

• Compile and run:


Hello Kitty Command Line
• Command-line:
• Download “HelloKitty.java”
• Open the command prompt (cmd.exe)
• “javac” is the Java compiler
• “java” is the interactive Java executable (JVM/JRE)
Creating a New Eclipse Project
Making your own Hello World!
• Create a new Java Class:
Customizing Your Eclipse
Eclipse Debugger
Project Structure
• module-info.java: module declaration*
• src: source code folder (.java)
• Organized into subfolders by package
• bin: bytecode folder (.class)
• Eclipse will store compiled code here
• res: resources folder (new source folder)
• Files used by project
• test: unit tests folder (new source folder)
• .classpath, .project, .settings: generated by eclipse
Comments
• Implementation comments
• Single-line:
1. /* … */
2. //
• Blocks:
/*
*
*/
• Documentation comments
/**
*
*/
Naming Conventions
• Classes and interfaces are nouns in PascalCase
• Methods are verbs in camelCase
• Variables are in camelCase
• Variable names should be meaningful
• “Self-documenting” – clearly identifies its use
• Exceptions are “throw-away” variables
• Temporary: i, j, k
• Integers: m, n
• Characters: c, d, e
• Constants in all uppercase SNAKE_CASE
Java Packages
• Package == namespace in C#
• Used to group related classes and interfaces (like a folder)
• Avoid naming conflicts, controls access and produces more
maintainable code
• camelCase

• Must use import package.name.Class for access


import java.util.Scanner;
import java.util.*;

• Can be built-in Java API or user-defined packages


Access Modifiers
Access Modifier Within Class Within Package Outside Package Outside Package
through Subclass
None (default) Yes Yes No No
private Yes No No No
protected Yes Yes Yes No
public Yes Yes Yes Yes

• protected in Java == internal in C#


• Access is different!
• In C#, protected members can only be accessed by the class itself and
any of its subclasses
• In Java, protected members can also be accessed by any classes within
the same package and subclasses outside the package!
Source File Structure
1. Class/interface documentation comment
2. Class/interface statement
3. Class/interface implementation comment
4. Class (static) variables
• Public, protected then private
5. Instance variables
• Public, protected then private
6. Constructors
7. Methods
• Grouped by functionality*
Coding Standards
• Each source file should contain only one public class or
interface
• Private classes and interfaces can be included but will always
be placed after the public class or interface
• Files should not be longer than 2000 lines
• Package statements before import statements
• Indentations is exactly 4 spaces
• Lines should not be longer than 80 characters
• Wrap statements that does not fit on a single line
• See examples
Keywords
C# Java C# Java C# Java C# Java
abstract abstract do do interface interface string String**
base super double double is instanceOf switch switch
bool boolean else else lock synchronized this this
break break extern native long long throw throw
case case false false new new true true
catch catch finally finally null null try try
char char float float object Object** using import
class class for/foreach for return return void void
const const* goto goto* sealed final volatile volatile
continue continue if if short short where extends
default default int int static static while while
Operators
• Almost all operators are the same in Java as C#!
• Assignment: =
• Arithmetic: +, -, *, /, %
• Combined arithmetic: +=, -+, *=, /+, %=
• Increment/decrement (prefix/postfix): ++, --
• Comparison: ==, !=, <, <=, >, >=
• Logical: !, &&, ||
• String concatenation: +
• Conditional: condition ? trueExpression : falseExpression
• Member access: object.attribute,
object.methodInvokation
• Array element access: array[indexValue]
Primitive (Simple) Data Types
• No decimal in Java
• Use float or double (can suffer from rounding errors*)

• No unsigned integers (ushort, uint, ulong)


• byte is signed (i.e. -128 to 127, sbyte in C#)

• No as keyword (safe cast operator) in Java!


• Widening (implicit) type casting will be done automatically
• Narrowing (explicit) type casting must be done manually
• Will lose precision
Primitive Wrapper Classes
• Primitive types in Java are not object-oriented!
• No methods defined
C# structs Java Primitive Type Java Wrapper Class
Boolean boolean Boolean
Byte byte Byte
Char char Character
Double double Double
Float float Float
Int16 short Short
Int32 int Integer
Int64 long Long
Other Types
• Built-in compound data types
• Strings are immutable in both languages
• DateTime struct in C#: java.util.Date* or java.time
package

• No user-defined value types (struct) in Java

• Enumerations in Java are classes


• Type-safe, can be extended by adding methods

• No pointers or delegates in Java


switch Statements
• Performs the same functionality as C# but Java allows
“fall-through”
• C# only allows this only if the case label has no statements

• Java 14 introduces the enhanced switch statement (also


called the switch expression)
Classes and Interfaces
• Inheritance syntax : in C#
• Class: extends
• Interface: implements

• Base class constructors are automatically invoked


• Constructor chaining follows the same rules but different keyword
• C#: base(), Java: super()

• No destructors in Java
• Similar concept are finalizers but use is discouraged*
• Finalizer of base class are not automatically called
Methods
• Parameters are always passed by copy
• No support for passed by reference (i.e. no in, ref, out)
• Can only return one value
• Return type in method signature is not void, use return statement

• Variable-length parameter list specified by Varargs


• Syntax: ... (same as params in C#)
• C#: params int[] args
• Java: Integer... args

• Must explicitly create getters and setters*


Exceptions
• Just like C#!
• try/catch/finally
• All exceptions derived from base Exception class
• Exceptions can be caught and rethrown (can be different
class)

• Java supports both unchecked and check exceptions


• Checked are exceptions that the calling method must handle
• By catching the exception or declaring that the exception should be
handled by its calling method via the throws clause
Arrays and Collections
• The Array class in Java is separated from the
Collections framework
• Arrays work the same in Java and C#
• But cannot be “resized” in Java (using the Array.Resize() in C#)
• Same functionality can be done with System.arraycopy() in Java
• No foreach statement in Java but same iteration can be
performed using for and the : operator

• Java supports all common types of collections


• ADT, xD arrays, maps, dictionaries, sets, sorted sets, lists,
vectors, queues, priority queues, stacks and many more!
Javadoc
• Generates HTML from specially formatted comments
from source code
• The standard Java API documentation
• Bookmark this for reference!
• Can use any HTML tags!
• Links!

• Many Javadoc tags has no equivalent in C# XML docs


• E.g. @author, @version
• Metadata of class
• Inherited and derived classes, implemented interfaces
Metadata Annotations
• @Override: to specify that a method will override the
method in the base class*
• Compilation error if there is no override

• @Deprecated: to indicate that a method has been


deprecated
• Compilation warning if used

• @SuppressWarnings: prevent compilation warnings


• Can add name of warning to suppress as argument
JUnit
• TDD is crucial in any language!
• JUnit == NUnit (unit testing level)

• Similar structure:
• Test class (fixture)
• Test method
• No TestCase attribute, must be separate test methods
• setup() and teardown()
• setUpBeforeClass(), tearDownAfterClass()
• Assertions
• Can be ran in eclipse just like a Java program! (test runner)
Streams and Serialization
• Streams are used for I/O to read and write from files,
storage and over networks
• Predefined Java streams: do not need to be instantiated
• Created by the JVM on initialization on the platform it’s running on
• Byte-oriented vs Character-oriented streams
• Chaining and buffering
• File I/O

• Serialization: class must implement the Serializable


interface*
• Fields that are not serialized must be marked transient**
Java Swing
• Event-driven* Java library for GUI applications
• Observer pattern or publisher/subscriber model
• Implemented as a “listener”
• Registering a “callback” method
• E.g. implements the ActionListener interface and overrides the
actionPerformed(ActionEvent e) method
• Implemented as a “observer”
• Using the Observer interface and Observable class
• Deprecated in Java 9

• There is no equivalent of event in Java**


Anonymous Inner Classes
• Nested classes are possible in both languages
• Java supports both static and non-static (inner classes)
• 1-1 relationship between inner and outer class
• Each instance of outer class has a corresponding instance of the inner
class which can access the outer class’s instance variables (no statics)

• Anonymous inner classes allows us to define only one


instance of a type that can be used
• Great for creating callback methods and implementing the
State Design Pattern
• E.g. Java GUI libraries

You might also like