0% found this document useful (0 votes)
3 views43 pages

1A Java 009

The document outlines the first lecture of CSCI 2010U - Data Structures, covering essential Java programming concepts, including Java's advantages, memory management, object-oriented differences from C++, and the Java development environment. It emphasizes the importance of class structure, the main method, and various data types and control structures in Java. Additionally, it includes administrative announcements regarding quizzes and lab attendance requirements.

Uploaded by

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

1A Java 009

The document outlines the first lecture of CSCI 2010U - Data Structures, covering essential Java programming concepts, including Java's advantages, memory management, object-oriented differences from C++, and the Java development environment. It emphasizes the importance of class structure, the main method, and various data types and control structures in Java. Additionally, it includes administrative announcements regarding quizzes and lab attendance requirements.

Uploaded by

mepol29555
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Brain Teaser / Born on This Day

Introduction to
Java
Lecture 1A

Eric J. Rapos

CSCI 2010U - Data Structures 1


Admin / Announcements
● Don’t forget that there is a quiz due Thursday night on the course outline
(all on Canvas).

● Labs will begin next week during your scheduled lab slot - in person
attendance at labs is required. Labs will be completed in the lab and graded
by the TA (similar to CSCI 2050U).

● You will need to complete Lab 0 (available on Canvas) before the end of this
week. No points, but you will not be able to succeed without it.

● Class attendance will be required for this course - there will be regular in
class activities and quizzes, worth 10% of your final grade.

CSCI 2010U - Data Structures 2


Review From Last Class
● It’s our first class, but we need to get back into a programming mindset.

● What kinds of things have you programmed in the past? What languages?

● What are the basic control structures in programming?

● What data types are you familiar with?

CSCI 2010U - Data Structures 3


Topics For Today - A Real Crash Course in Java!
● Why Java?
● Java vs. C++
● Java Environment, Basics, and Nuances
● Writing, Building, and Executing a Java Program
● Activity 1B1: My First Java Program
● Review of Data Types and Control Structures
● Exception Handling
● Coding Conventions
● Activity 1B2: CodingBat Problems

CSCI 2010U - Data Structures 4


Why Java?

CSCI 2010U - Data Structures 5


Why Java?
● Platform independence

● Large standard library

● Robust community and ecosystem

● Add another language to your programming repertoire

● Longevity and prevalence (it’s still #2 in usage:


[Link]

CSCI 2010U - Data Structures 6


Java vs. C++

CSCI 2010U - Data Structures 7


Memory Management
C++ Java

● Manual memory management through ● Automated garbage collection when no


allocation and deletion longer used

● Due to manual control, it can lead to ● Typically safer as it prevents common


errors such as dangling pointers and memory management errors possible in
memory leaks. C++.

● Generally manual collection is more ● Can introduce additional pause times, so


efficient since there are no interruptions while safer, it can introduce performance
from a garbage collector. issues - however they are usually minimal.

CSCI 2010U - Data Structures 8


Object Oriented Differences
● Single vs. Multiple Inheritance
○ Java only allows for single inheritance, meaning each class can only inherit from one parent

● Interfaces vs. Abstract Classes


○ Java’s answer to Abstract Classes are called Interfaces
○ Essentially a way to define a contract that classes can implement
○ Interfaces can contain abstract methods (methods without a body) and default methods
(with a body)

CSCI 2010U - Data Structures 9


Access Modifiers
Modifier C++ Java

public Members (variables, functions, classes) declared as Members (fields, methods, classes) declared as
public are accessible from any other part of the public are accessible from any other class.
program.

protected Members declared as protected are accessible within Members declared as protected are accessible
the same class and by derived classes. In C++, within the same package and by subclasses. In
protected members are accessible only to subclasses Java, protected members are also accessible to
and not to other classes in the same namespace. other classes in the same package, in addition to
subclasses.

private Members declared as private are accessible only Members declared as private are accessible only
within the same class. within the same class.

Package-Private C++ does not have a direct equivalent of Java's A default (package-private) access level that is
(default - no keyword) package-private access. Access is explicitly specified used when no access modifier is specified.
as public, protected, or private. Members are accessible only within the same
package.

CSCI 2010U - Data Structures 10


Other Differences // Superclass
class Animal {
public void makeSound() {
● Method Overloading: both Java and C++ }
[Link]("generic sound");

support method overloading, allowing }

multiple methods with the same name but // Subclass


class Dog extends Animal {
different parameter lists @Override
public void makeSound() {
● Method Overriding: // Calling the superclass method
[Link]();
○ Both Java and C++ allow subclasses to override [Link]("Bark");
methods of a superclass }
○ Java uses the @Override annotation to indicate public static void main(String[] args) {
and ensure a method is overriding a superclass Dog dog = new Dog();
[Link]();
method }
○ Java has a super keyword is used to call }
superclass methods

CSCI 2010U - Data Structures 11


Java Environment, Basics, and Nuances

CSCI 2010U - Data Structures 12


Java Environment
● Java Virtual Machine (JVM)
○ The JVM is a virtual machine that enables Java applications to run on any device or
operating system without modification. It provides a runtime environment in which Java
bytecode can be executed.
○ Responsible for: Bytecode execution, memory management, and platform independence
● Java Runtime Environment (JRE)
○ The JRE provides the libraries, Java Virtual Machine (JVM), and other components to run
applications written in Java. End users need the JRE to run Java applications on their
systems.
● Java Development Kit (JDK)
○ The JDK is a full-featured software development kit required to develop Java applications
and applets. It includes the JRE, development tools, and additional libraries.

CSCI 2010U - Data Structures 13


Java Development Environment
● As with any programming language, Java requires an environment in which
you will develop programs. You have several options for Java programming,
explained further in Lab #0.
● Popular Options:
○ IntelliJ IDEA - recommended for this course, simple IDE with plenty of features (I’ll use in
class)
○ VSCode - another very popular IDE with similar features and useful with other languages
○ Text Editor and Command Line - for the programming purists among us, and it’s simple

CSCI 2010U - Data Structures 14


Main Method and Class Structure
● All Programs Must Be Part of a Class:
○ In Java, every program must be encapsulated within a class. This is fundamental to the language's structure.
● Instance Classes (Non-Static Classes):
○ Classes without the static modifier are instance classes.
○ Instance classes are used to create objects (instances) at runtime.
○ Fields and methods defined in instance classes are associated with individual objects of that class.
● Static Classes:
○ Classes with the static modifier are static classes or static nested classes.
○ Static classes do not require an instance of the enclosing class to be instantiated.
○ They are typically used for methods or variables that do not depend on instance-specific state, such as utility methods or
constants.
● Purpose of Instance Classes:
○ Used to define the structure and behavior of individual objects.
○ Fields represent object-specific data, while methods operate on that data.
● Purpose of Static Classes:
○ Used for methods that do not need to access instance-specific data.
○ Can be used as helper classes or to encapsulate utility functions.
● Main Method Requirement:
○ The main method in Java must be declared as static.
○ It serves as the entry point of the program and does not require an instance of the class to be executed.

CSCI 2010U - Data Structures 15


// Example of Instance Class (Non-Static Class)
public class InstanceClass {
// Instance variables
private int num;
// Example of Static Class (Static Nested Class)
public class StaticClass {
// Constructor
// Static nested class
public InstanceClass(int num) {
static class Helper {
[Link] = num;
// Static method
}
public static int add(int a, int b) {
return a + b;
// Instance method
}
public void printNumber() {
}
[Link]("Number: " + num);
}
// Main method (entry point)
public static void main(String[] args) {
// Main method (entry point)
// Calling static method without creating
public static void main(String[] args) {
an instance of StaticClass
// Creating an instance of InstanceClass
int sum = [Link](5, 7);
InstanceClass instanceObject = new
[Link]("Sum: " + sum);
InstanceClass(10);
}
// Calling instance method
}
[Link]();

}
}

CSCI 2010U - Data Structures 16


Construct C++ Java Notes

Class Definition class MyClass { public class MyClass { Very similar, note the
// Class members // Class members removed semicolon for
}; } Java classes, and the use
of the modifier.

Method void myMethod() { public void myMethod(){ Java continues to use its 4
Declaration // Method body // Method body modifiers (covered
} } previously) for methods.

Constructors MyClass() { public MyClass() { Mainly the use of the


// Constructor body // Constructor body access modifier is
} } different.

Inheritance class ChildClass : public ParentClass { public class ChildClass extends ParentClass Quite different syntax.
// Class members {
}; // Class members
}

Method void myMethod() override { @Override Quite different syntax.


Overriding // Method body public void myMethod() {
} // Method body
}

Main Method int main() { public static void main(String[] args) { Java uses many modifiers
// Main method body // Main method body and arguments for the
} } main method.

CSCI 2010U - Data Structures 17


Common Libraries and APIs
● [Link] Package:
○ Provides fundamental classes and utilities that are universally used in Java programming, ensuring students
understand basic types and utilities.
● [Link] Package:
○ Essential for understanding data structures like lists, maps, sets, and basic utilities for manipulating
collections.
● Input/Output (I/O) APIs:
○ Basic file handling and input/output operations, foundational for reading from and writing to files.
● Exception Handling:
○ Introduction to handling errors and exceptions in Java programs, critical for robust programming practices.
● [Link]:
○ Simple and intuitive API for reading input, which is practical for beginner programs and exercises.
● [Link]:
○ Essential for performing common mathematical operations, which students will frequently encounter in
programming tasks.

CSCI 2010U - Data Structures 18


Writing, Building, and Executing a Java
Program

CSCI 2010U - Data Structures 19


Writing a Java Program
● In your IDE, create a new public class MyFirstProgram {

project and main class - you public static void main(String[] args) {
int age = getAge(1999, false);
always need to have a class, and [Link](“I am “ + age + “ years old!);
}
the filename must match the
class name. public static int getAge(int year, boolean hadBirthday) {
int age = 2024 - year;
● Within your main class, you if(!hadBirthday) {
age–-;
need to have a main method, as }
return age;
this will be the starting point of }
}

execution.
● You can create other methods
and classes as necessary.

CSCI 2010U - Data Structures 20


Building Your Program
● Using an IDE
○ Most IDEs will have a button, menu option, and/or keyboard shortcut to build and run your
program. You’ll need to find it on yours (I’ll show an example).

● Using the command line


○ You will need to use the javac command to build an executable of your program:

javac [Link]

○ This will create a .class file that can be run.

CSCI 2010U - Data Structures 21


Running Your Program
● Using an IDE
○ This is usually combined with the build step and the IDE will run your program following the
build.
● Using the Command Line
○ You will need to use the java command on the generated class file (do not add .class) to run
the program

java MyFirst Program

Output:

I am 24 years old!

CSCI 2010U - Data Structures 22


Activity 1B1: My First Java Program

CSCI 2010U - Data Structures 23


Review of Data Types and Control Structures

CSCI 2010U - Data Structures 25


Primitive Data Types in Java
Data Type Description Size Default Value Example Usage

boolean Represents a boolean value (true or false). Not specified false boolean flag = true;

byte Represents an 8-bit signed integer. 8 bits 0 byte b = 100;

short Represents a 16-bit signed integer. 16 bits 0 short s = 1000;

int Represents a 32-bit signed integer. 32 bits 0 int i = 100000;

long Represents a 64-bit signed integer. 64 bits 0L long l = 100000L;

float Represents a single-precision 32-bit IEEE 754 floating 32 bits 0.0f float f = 123.45f;
point.

double Represents a double-precision 64-bit IEEE 754 floating 64 bits 0.0d (or 0.0) double d = 123.456;
point.

char Represents a 16-bit Unicode character. 16 bits '\u0000' char c = 'A';

CSCI 2010U - Data Structures 26


The Basic Control Structures
If Statements While Loops Do While Loops For Loops Switch Statements
int num = 10; int count = 1; int count = 1; for (int i = 1; i <= 5; i++){ int dayOfWeek = 3;
[Link]. String dayName;
String res = “”; while (count <= 5) { do { println("Count: " switch (dayOfWeek) {
[Link]. [Link]. + i); case 1:
if (num > 0) { println("Count: " println("Count: " } dayName = "M";
res = “positive”; + count); + count); break;
} else if (num < 0) { count++; count++; case 2:
res = “negative”; } } while (count <= 5); dayName = "Tu";
} else { break;
res = “zero”; case 3:
} dayName = "W";
break;
[Link]( case 4:
“The number is “ + dayName = "Th";
res); break;
case 5:
dayName = "Fr";
break;
default:
dayName = "Er";
}
[Link]("Day
is: " + dayName);

CSCI 2010U - Data Structures 27


Ternary Operators - A Neat Shortcut
● The ternary operator (condition) ? expression1 : expression2
evaluates a condition and returns one of two expressions based on whether the
condition is true or false.
int a = 10;
int b = 5;
int max = (a > b) ? a : b;
[Link]("Max value is: " + max);
// Outputs: Max value is: 10

○ Condition: (a > b) checks if a is greater than b.


○ True Case: If a is greater than b, max is assigned the value of a.
○ False Case: If a is not greater than b, max is assigned the value of b.
○ In this example, since a is 10 and b is 5, max will be 10 because a > b is true.
● Benefits:
○ Conciseness: Allows compact conditional assignments in a single line.
○ Readability: Clearly expresses conditional logic without the verbosity of an if-else statement.
● The ternary operator is useful for simple conditional assignments and helps in
writing more streamlined code when the logic is straightforward.
CSCI 2010U - Data Structures 28
Exception Handling

CSCI 2010U - Data Structures 29


Exceptions in Java
● In Java, exceptions are events that occur during the execution of a program
that disrupts the normal flow of instructions.
● Exceptions are used to handle situations like division by zero, accessing an
array out of bounds, or file not found errors.
● They represent exceptional conditions that may arise during runtime,
such as errors or unexpected situations that prevent the program from
continuing its execution as intended.
● Exceptions in Java are categorized into checked exceptions (which must be
handled or declared) and unchecked exceptions (which do not need to be
explicitly handled).

CSCI 2010U - Data Structures 30


Exception Hierarchy

CSCI 2010U - Data Structures 31


Throwing Exceptions
● The simplest, but not necessarily most public class Main {

elegant way of dealing with exceptions is public static void main(String[] args)
throws ArithmeticException {
to simply declare that they may be int a = 10;
int b = 0;
thrown, and let someone else (the calling int result = divide(a, b);
[Link]("Result: " + result);
method) deal with them. However, if your }

main method throws an exception, it will public static int divide(int a, int b)
throws ArithmeticException {
cause the program to crash anyway. }
return a / b;

}
● This is done using the throws keyword.

CSCI 2010U - Data Structures 32


try/catch Blocks public class TryCatchExample {

public static void main(String[] args) {


try {
● The more helpful and safe int[] numbers = {1, 2, 3};
int index = 4; // Trying to access an index out of bounds
method of dealing with
exceptions is to use int number = numbers[index];
// This line will throw an ArrayIndexOutOfBoundsException
try/catch blocks.
// This line will not execute if an exception is thrown
● You surround code that may [Link]("Num at ind " + index + ": " + number);
cause an exception in a try } catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Array index out of bounds");
block, and then you write an } catch (ArithmeticException e) {
exception handler in a catch }
[Link]("Error: Arithmetic exception");
catch (Exception e) {
block. [Link]("Error: Some other exception");
} finally {
● You need to prepare to catch [Link]("Finally block executed");
the appropriate type of }

exception, and can actually [Link]("End of program");


}
provide multiple handlers for }
different types of exceptions.

CSCI 2010U - Data Structures 33


Best Practices and Coding Standards

CSCI 2010U - Data Structures 34


Naming Conventions
● Classes:
○ Use nouns, capitalize the first letter of each word (PascalCase).
○ Example: MyClass
● Methods:
○ Use verbs or verb phrases, capitalize the first letter of each word (camelCase).
○ Example: calculateTotal()
● Variables:
○ Use meaningful names (camelCase).
○ Example: totalCount
● Constants:
○ Use ALL_CAPS_WITH_UNDERSCORES.
○ Example: MAX_SIZE

CSCI 2010U - Data Structures 35


Code Formatting
● Use consistent indentation.
○ Many IDEs typically use 4 spaces per level, however the Google Java Style Guide uses only 2
spaces to save horizontal spaces. I recommend changing your settings to 2 spaces.

● Use braces {} for all control structures (if, for, while, do-while, switch) even
for single statements.
○ No line break before the opening brace, except as detailed below.
○ Line break after the opening brace.
○ Line break before the closing brace.
○ Line break after the closing brace, only if that brace terminates a statement or terminates
the body of a method, constructor, or named class. For example, there is no line break after
the brace if it is followed by else or a comma.
● Limit line length (commonly 80-120 characters per line, we’ll use 100).

CSCI 2010U - Data Structures 36


Comments
● COMMENT YOUR CODE!
○ Provide justification for choices and explanations for non-obvious behavior.
○ Do not over-comment your code; avoid redundant comments.
● // Use single line comments for short simple details.

● /*
* Use multi-line comments for more complex
* blocks of comments that provide longer
* descriptions.
*/

CSCI 2010U - Data Structures 37


JavaDoc Comments
/**
● JavaDoc is a tool used to generate API * Calculates the sum of two numbers.
documentation in HTML format from Java source *
* @param num1 The first number.
code. It helps developers document their code * @param num2 The second number.
effectively so that others (and themselves) can * @return The sum of num1 and num2.
* @throws IllegalArgumentException If either num is negative.
understand its usage without diving into the * @see #calculateSum(int, int)
implementation details. */
public int calculateSum(int num1, int num2)
● JavaDoc comments are written in a specific format, throws IllegalArgumentException {
starting with /** and ending with */, allowing for if (num1 < 0 || num2 < 0) {
throw new IllegalArgumentException("Neg. number.");
structured documentation. }
● Tags: JavaDoc supports various tags to provide return num1 + num2;
}
additional information:
○ @param: Describes a method or constructor parameter.
○ @return: Describes the return value of a method.
○ @throws: Describes exceptions thrown by a method.
○ @see: References other classes or methods. We will use JavaDoc Comments
○ @deprecated: Marks a class or method as deprecated. for ALL Methods and Classes!

CSCI 2010U - Data Structures 38


Java Best Practices & Tips and Tricks
● Master basic OOP concepts (classes, objects, inheritance, polymorphism)
● Follow naming conventions strictly
● Handle exceptions properly using try-catch blocks
● Utilize standard Java libraries effectively
● Learn to write and call methods to modularize your code
● Use meaningful comments to document your code’s intent and logic
● Familiarize yourself with debugging techniques and tools in your IDE
● Keep learning and exploring new features and best practices in Java

CSCI 2010U - Data Structures 39


Activity 1B2: CodingBat Problems

CSCI 2010U - Data Structures 40


Review
● Why Java?
● Java vs. C++
● Java Environment, Basics, and Nuances
● Writing, Building, and Executing a Java Program
● Activity 1B1: My First Java Program
● Review of Data Types and Control Structures
● Exception Handling
● Coding Conventions
● Activity 1B2: CodingBat Problems

CSCI 2010U - Data Structures 42


Next Class
● Using Objects in Java
● Java Arrays
● Lists in Java
● ArrayLists
● Arrays vs. ArrayLists

CSCI 2010U - Data Structures 43


Reminders
● If you haven’t yet completed Lab 0, do so as soon as possible.

● There is a quiz on Canvas that is due tonight (Thursday), based on the course
outline. It is meant to ensure you are familiar with the course expectations
and content.

● Labs start next week in-person - you must attend the lab in person to get
credit.

CSCI 2010U - Data Structures 45


Brain Teaser / Born on This Day

The Answer!

CSCI 2010U - Data Structures 46

You might also like