0% found this document useful (0 votes)
6 views85 pages

Lecture 2 (Java Basics)

The lecture focuses on using Java to learn data structures and algorithms, covering basic concepts such as JDK, JVM, and object-oriented programming features. It emphasizes practical coding skills and the advantages of Java, including its ease of learning and platform independence. The course will not cover advanced topics like inheritance, GUI, or Android app development, focusing instead on foundational Java knowledge relevant to data structures.

Uploaded by

Tiffany Olivia
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)
6 views85 pages

Lecture 2 (Java Basics)

The lecture focuses on using Java to learn data structures and algorithms, covering basic concepts such as JDK, JVM, and object-oriented programming features. It emphasizes practical coding skills and the advantages of Java, including its ease of learning and platform independence. The course will not cover advanced topics like inheritance, GUI, or Android app development, focusing instead on foundational Java knowledge relevant to data structures.

Uploaded by

Tiffany Olivia
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

(Materials of this lecture are NOT included in the midterm and final exams)

Yixiang Fang
School of Data Science (SDS)
The Chinese University of Hong Kong, Shenzhen
 Why do we use Java to learn data structures?

 What will we learn and NOT learn about Java?

 Basic knowledge of Java


◦ JDK/JVM/JRE
◦ Keywords, declaration, expressions, class/object, method,
others

2
 This course is not just about reading and writing — we need to write
codes by implementing data structures and algorithms

 Java is one of the most frequently used programming languages


◦ It is one of the easy-to-use programming languages to learn
◦ Java is platform-independent, i.e., write once, run anywhere!
 Java program is compiled into bytecode, which can be run on multiple platforms

 Used for
◦ Developing Android Apps
◦ Helps you to create Enterprise Software
◦ Wide range of mobile applications
◦ Scientific computing
◦ Big data analytics (e.g., Hadoop and Spark)
◦ …
◦ Much more!

3
 Advantages of Java
◦ Easier to learn
◦ No pointer, safer
◦ Automatic memory management, including garbage collection
◦ Cross platforms
◦ More powerful standard libraries
◦ Java and Java-based IDEs are often provided free of charge
◦ Often used for research (e.g., Hadoop and Spark)
◦ …

4
 What will we learn?  What will we NOT learn?
◦ JDK, JVM, JRE ◦ Interface
◦ Keywords ◦ Abstract class
◦ Simple declarations ◦ Inheritance
◦ Statements
◦ Classes/objects ◦ GUI
◦ Methods ◦ Multi-thread
◦ Exceptions ◦ Garbage collection
◦ Network communication
◦ Web design
◦ Android Apps development
◦ …
◦ Many others

Only focus on the basic knowledge of Java that is used for


implementing the data structures and algorithms in this course!
5
 Java Development Kit (JDK)
◦ A software development environment which is used to develop Java
applications and applets

 Java Runtime Environment (JRE)


◦ It provides the minimum requirements for executing a Java application; it
consists of JVM, core classes, etc.

 Java Virtual Machine (JVM)


◦ An abstract machine that doesn't physically exist, a specification that
provides a runtime environment in which Java bytecode can be executed

Java is platform-independent,
but JVM is not!

6
 Everything in Java is an object
◦ We organize our software as a combination of different
types of objects that incorporate both data and behavior
◦ Class “Object” is the root class for every derived class in
Java

 OOP features:
◦ Object
◦ Class
◦ Inheritance
◦ Polymorphism
◦ Abstraction
◦ Encapsulation

7
 Source codes
◦ Declare a class with name
 class Welcome{…}

◦ Declare the main method


 public static void main(String args[ ]){…}
 Java main method is the entry point of any java program

◦ Print “Welcome to Java!” to the console


 [Link](“Welcome to Java!")

8
9
 Install a JDK (Java Development Kit)
◦ Install an OpenJDK
 e.g., Java SE DK 16
◦ Set up environment variables:
 JAVA_HOME: Points to the base of the JDK installation. e.g.,
“C:\Program Files\Java\jdk___VERSION”
 PATH: Add “%JAVA_HOME%\bin”.
 Verify installation (e.g., on Mac)

 Install an IDE or editor


◦ Eclipse (my personal choice), VS Code, Notepad…

 A concise guide: [Link]


[Link]
10
11
12
13
14
15
 Java keywords (reserved words)
◦ Keywords are particular words, which acts as a key to a code
◦ Keywords cannot be used as variable or object names

 Keywords of primitive types


◦ int: used to declare a variable that can hold a 32-bit signed integer
◦ boolean: used to declare a variable as a boolean type (true or false)
◦ double: used to declare a variable that can hold a 64-bit floating-
point numbers
◦ char: used to declare a variable that can hold unsigned 16-bit
Unicode characters
◦ short: used to declare a variable that can hold a 16-bit integer
◦ long: used to declare a variable that can hold a 64-bit integer
◦ float: used to declare a variable that can hold a 32-bit floating-point
number
◦ byte: used to declare a variable that can hold an 8-bit data values
16
 Keywords of loops
◦ for: used to create a for loop (a variable initialization, a boolean
expression, and an incrementation)
◦ while: used to create a while loop, which tests a boolean expression
and executes some statements if the expression is true
◦ continue: used to continue the loop; it continues the current flow of
the program and skips the remaining code at the specified condition
◦ break: used to break loop or switch statement; it breaks the
current flow of the program at specified condition

 Keywords of conditions
◦ if: Java if keyword tests the condition, and the if block is executed
if the condition is true
◦ else: used to indicate the alternative branches in an if statement

 Keywords of classes and objects


◦ class: used to declare a class
◦ new: used to create new objects
17
 Keywords of exceptions
◦ try: used to start a block of code that will be tested for exceptions,
and the try block must be followed by either catch or finally block
◦ catch: used to catch the exceptions generated by try statements,
and it must be used after the try block only
◦ finally: used to create a block of code following a try block; its
block always executes whether an exception occurs or not

 Keywords of others
◦ import: used to make classes and interfaces available and accessible
to the current source code
◦ package: used to declare a Java package that includes the classes
◦ public: as an access modifier, it is used to indicate that an item is
accessible anywhere, and it has the widest scope among all other
modifiers
◦ return: used to return from a method when its execution is
complete
◦ null: used to indicate that a reference does not refer to anything
18
 Variable in Java is a data container, storing the data values
during program execution

 Every variable is assigned a data type which designates the


type and quantity of value it can hold

 Variable is a memory location name of the data

 To use variables
◦ Variable declaration
◦ Variable initialization

19
 Variable declaration

type

variable
semicolon
name

 Numeric expressions are written in much the same


way as in other languages

20
 Three types of variables
◦ Local variables are declared inside the body of a method

◦ Instance variables are defined without STATIC keyword, and they are
defined outside a method declaration, i.e., they are object specific

◦ Static variables are initialized only once, at the start of the program
execution; These variables should be initialized first, before the
initialization of any instance variables, i.e., they are Class specific
21
 Statements can be grouped in blocks using “{ }”
 If and if-else statements

 Comparison operators: >, <, ==, >=, <=, !=

22
 More about Boolean expressions

 while loop statement: need the stopping criterion

23
 for loop statement
◦ Initial value of value i
◦ Stopping criterion of the loop
◦ How to change the value of i in each iteration

24
 A class is a blueprint or prototype
that defines the variables and the
methods (functions) common to all
Java objects of a certain kind

 An object is a specimen of a class


◦ An object is an instance of a class
◦ Software objects are often used to
model real-world objects you find in
everyday life

25
 A class declaration contains
◦ A set of attributes (called instance variables)
◦ A set of functions (called methods in Java)

 Methods in Java
◦ Main methods: public static void main(String [ ] args){…}
◦ Constructor methods: public Turtle( ){…}
◦ General methods: public void jumpTo(int newX, int newY) {...}

26
 Java constructor
◦ A special method for initializing a newly created object and
is called just after the memory is allocated for the object

◦ It can be used to initialize the objects to desired values or


default values at the time of object creation

◦ It is not mandatory to write a constructor for a class

 Rules for creating a java constructor


◦ It has the same name as the class
◦ It should not return a value (not even void)
27
 Java method
◦ Method name, input parameters, method body, return type

28
 Access modifiers
◦ The public keyword is used to declare that something can be
accessed from other classes

◦ The protected keyword specifies that something can be accessed


from within the class and all its subclasses, but not from the outside

◦ When we do not mention any access modifier, it is called default


access modifier, and the scope of this modifier is limited to the
package only

◦ The private declaration means that those attributes cannot be


accessed outside of the class
 In general, attributes should be kept private

29
 In Java, statements can only be written within
methods in classes
◦ There must be some method which is called by the system
when the program starts executing, which is main method

 Notes
◦ static keyword: when the main method is called, it is not
associated with an object, but with the class
◦ The parameter args: if the Java interpreter is given any
more information than the class name, this data is passed
on to the main method in this parameter
30
 The keyword new is used to
create an object of a class

 Calling methods in objects

◦ Java has garbage collection, so


no need to destroy objects
manually

31
 Many things can go wrong during the execution of a
program (programmers may introduce faults)
◦ E.g., division by zero or calling a method with a null reference

 Throw exceptions
◦ E.g., consider a method to read a positive integer from the
keyboard; what if the input character is not an integer?

32
 Catch exceptions
◦ The statement(s) within the try clause are executed as
usual, but whenever an exception occurs, the try clause is
interrupted and the statements within the corresponding
catch clause are executed

33
 Packages
◦ Package in Java is a collection of classes, sub-packages,
and interfaces
◦ It helps organize your classes into a folder structure and
make it easy to locate and use them
◦ More importantly, it helps improve code reusability

34
 Comments
◦ Single sentence: two forward slashes //
◦ A block of codes: /* xxx */

35
 Array
◦ Declaration

◦ Initialization What is the


maximum
array size?

◦ Use arrays: 0 ~ size-1

36
37
 More online materials
◦ [Link]
[Link]

◦ [Link]
n/EDA040/common/[Link]

◦ Book: Think in Java

38
Materials for self-learning

39
 A string is a sequence of
characters, or an array of
characters

 Use String class to handle


strings

40
 Print something: writing to the console
◦ [Link](xxx)
◦ [Link](xxx)

41
 Type conversion (casting)
◦ Assign a real value to an integer value: need a cast

◦ Assigning an integer to a real variable does not need casting

42
 ArrayList is a data structure that can
◦ be stretched to accommodate additional elements within itself
◦ shrink back to a smaller size when elements are removed

 Notes
◦ A key data structure for handling dynamic behaviors of elements
◦ When the number of elements is larger than its initial size, it
creates another larger interval array and then copied the
existing elements to the new interval array
◦ Although it provides more flexibility, it often take more space
cost than an array
43
 Keyword “this”
◦ this keyword in Java is a reference variable that refers to the
current object of a method or a constructor
◦ The main purpose of using this keyword is to remove the confusion
between class attributes and parameters that have same names

44
 In Fibonacci series, next number is the sum of previous
two numbers.
◦ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.
◦ The first two numbers of Fibonacci series are 0 and 1.

 Two ways to write the Fibonacci series program:


◦ Fibonacci Series without using recursion
◦ Fibonacci Series using recursion

 We will see
◦ Defining variables
◦ Loop
◦ Recursion
 Given two numbers, find the greatest common
diviser (GCD)
◦ for example, GCD of 15 and 20 is 5; GCD of 7 and 5 is 1.
 Algorithm 1
◦ iterate from the smaller number given to 1
 Algorithm 2 (Euclid's Algorithm)
◦ if we subtract the smaller number from the larger number,
the GCD doesn't change
◦ when the smaller number exactly divides the larger number,
the smaller number is the GCD of the two given numbers.
 Verify prime number in Java: Prime number is a
number that is greater than 1 and divided by 1 or
itself only. For example, 2, 3, 5, 7, 11, 13, 17.... are
the prime numbers.
 A palindrome number is a number that is same after
reverse.
◦ 545, 151, 34543, 343, 171, 48984 are the palindrome
numbers.
 Algorithm
◦ Get the number to check for palindrome
◦ Hold the number in temporary variable
◦ Reverse the number
◦ Compare the temporary number with reversed number
◦ If both numbers are same, print "palindrome number"
◦ Else print "not palindrome number"
 The object is a basic building block of an OOPs language.
We cannot execute any Java program without creating
an object.

 Five ways to create an object in Java.


◦ Using new Keyword: the most popular way to create an object or
instance of the class. When we create an instance of the class by using the
new keyword, it allocates memory for the newly created object and also
returns the reference of that object to that memory. The new keyword is
also used to create an array.
◦ Using clone() method
◦ Using newInstance() method of the Class class
◦ Using newInstance() method of the Constructor class
◦ Using Deserialization
 ASCII: American Standard Code for Information
Interchange.
◦ A 7-bit character set contains 128 (0 to 127) characters.
◦ It represents the numerical value of a character.
◦ Example: ASCII value of A is 65

 Two ways to print ASCII value:


◦ Assigning a Variable to the int Variable
◦ Using Type-Casting
 Iterate through the string and count the
characters.
◦ STEP 1: START
◦ STEP 2: DEFINE String string = "The best of both worlds".
◦ STEP 3: SET count =0.
◦ STEP 4: SET i=0. REPEAT STEP 5 to STEP 6 as long as
i<[Link]
◦ STEP 5: IF ([Link](i)!= ' ') then count =count +1.
◦ STEP 6: i=i+1
◦ STEP 7: PRINT count.
◦ STEP 8: END
 Algorithm
◦ Define a string or read from the user.
◦ Declare a variable to count the number of punctuations and
initialized it with 0.
◦ Match each character with the punctuation marks (!, . , ' , -
, " , ? , ; ). If any character in the string is matched,
increase the count variable by 1.
◦ Print the count variable that gives the total number of
punctuations.
 Replace lower-case characters in a string to upper-case
and vice versa.
◦ STEP 1: START
◦ STEP 2: DEFINE a string str = "Great Power".
◦ STEP 3: DEFINE newstr as StringBuffer object .
◦ STEP 4: SET i=0. REPEAT STEP 5 to STEP 6 as long as
i<[Link]().
◦ STEP 5: IF lower-case character encountered then CONVERT in
upper-case. ELSEIF upper-case character encountered then
CONVERT in lower-case.
◦ STEP 6: i=i+1
◦ STEP 7: PRINT newstr.
◦ STEP 8: END
 Check whether string 2 is a rotation of string 1:
Concatenate string 1 with string 1. If string 2 is
present in concatenated string then, string 2 is
rotation of string 1.
◦ STEP 1: START
◦ STEP 2: DEFINE String str1 = "abcde", str2 = "deabc"
◦ STEP 3: IF length of str1 not equals to str2 then PRINT
"No" else go to STEP 4
◦ STEP 4: CONCATENATE str1 with str1.
◦ STEP 5: IF str2 present in str1 then PRINT "Yes" else
PRINT "No".
◦ STEP 6: END
 The File class is an abstract representation of file
and directory pathname.
◦ A pathname can be either absolute or relative.

 The File class have methods for working with


directories and files:
◦ creating new directories or files
◦ deleting and renaming directories or files
◦ listing the contents of a directory, etc.

 VERY USEFUL IN THIS CLASS

[Link]
 Java FileInputStream class obtains input bytes
from a file.
◦ used for reading byte-oriented data (streams of raw bytes)
such as image, audio etc.
◦ can also read character-stream data.
◦ For reading streams of characters, it is preferred to use
FileReader.

 FileOutputStream write primitives values into a file.


◦ Write byte-oriented and character-oriented data.
◦ For character-oriented data, it is preferred to use
FileWriter.
[Link]
[Link]
 Both FileReader and FileWriter classes are
character-oriented (for text file)
◦ FileReader is used to read data from the file.
◦ It returns data in byte format like FileInputStream class.

◦ FileWriter is used to write character-oriented data to a


file.
◦ Unlike FileOutputStream class, no need to convert string
into byte array.

You might also like