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

Report About Java

Uploaded by

nelsonchandra84
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)
16 views

Report About Java

Uploaded by

nelsonchandra84
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
You are on page 1/ 100

BI3122 Programming in Java

Final Exam – Module


By: Nelson Chandra / 20010008
Introduction
Definition of Java
• Java programming languange is an object-oriented programming
language that commonly used to develop back-end parts of software,
Android applications, websites, and runs on a variety of platforms.
• When a programmer creates a Java application, the produced code
(also known as bytecode) may operate on a wide range of operating
systems, including Windows, Linux, and Mac OS.
• Software: IntellIJ, Eclipse.
Session 1
How to install Java for Windows OS?

• Go to https://www.oracle.com/java/technologies/, and click Java SE


How to install Java for Windows OS?

• Click x64 installer, and wait for the downloading process.


How to install Java for Windows OS?

• Follow the instructions.


How to install intellIJ?
• Go to https://www.jetbrains.com/help/idea/installation-guide.html
• Click “Get intellIJ IDEA”.
How to install intellIJ?
• Click “download .exe” in the community part.
How to install intellIJ?
• Follow the instructions.
Creating the first project

To create the new project, click file on the top, then click
“New”, then follow the procedure.
Exploring the intelIJ interface

The class that is used is “hello”, “System.out.println” command is used to print the
output. The output is “Hello java”.
How to install eclipse?
• Go to https://www.eclipse.org/downloads/packages/installer
• Click “downdoad x86_64”.
How to install eclipse?
How to install eclipse?
Session 2
Variables
• A variable is a placeholder for any given piece of information. A user
can enter a number, such as 4, into a variable and update it whenever
they want. A value is the data that is stored in a variable and can vary
during the program's execution. A number isn't always the value
stored in a variable.
Variables

In the output, “Hello java” comes from the ‘System.out.println(“Hello java”)’, “15” comes from
“myFirstNumber = (10+5)”, “1” comes from “mySecondNumber = 18”, “33” comes from
“myThirdNumber = myFirstNumber + mySecondNumber”, and “967” comes from
“myNumber”cvariable, which is “1000 – myThirdNumber”. myThirdNumber is the total of the
first number and second number. “System.out.println” command is used to print the output.
Variables
• There are 3 types of variables in Java:
• Local variable
• A local variable is a variable that only exists within a method or function. The
variable is unknown to the program outside of the function's scope.

• A local variable cannot be accessed directly outside a function.


Variables
• Java Instance Variable
• Instance variables are variables that are declared only in the body of a
class, not in any of its methods. Despite having the same identity,
these vary with each instance of the class produced.
Variables
• Static Variables in Java
Primitive Data Types (Byte, Short, Int, and Long)

This section has a same concept with the variables, but different in the type of the number. This
section uses the byte, short, int, and long.
Primitive Data Types

“L” in “10L” is the long, the output will follow the criteria of the types of the number.
Primitive Data Types (Float and Double)

In this section, float and double are the types of the number. “d” is double, and “f” is float.
Primitive Data Types (Char and Boolean)

Char refers to a basic data type. It's where character-type variables and methods are
declared. It has the ability to store unsigned 16-bit Unicode characters. Boolean
expression is a Java expression that produces a true or false value when evaluated.
Conditional statements such as if, while, and switch employ Boolean expressions.
Understanding Strings and Finishing Up Primitive
Data Types

The result of “LastString” is 1050, it means that “LastString” will be joined with “myInt”, not amounted
because it has the different of the number type.
Operators in Java
Operators in Java

• In this code, the concept is join the result of number with the
previous number. In the “Result is now = “ output, “++” means
addition by 1, “—“ means subtraction by 1, “+-“ means addition by
the various number, “-=” means subtraction, “*=” means
multiplication, and “/=” means division, “%” means modulus, “>”
means great, and “<” means less than.
More On Operator and Operator Precedence

The output of this section is “Total = 820.0” and “Total was over the limit”, r is the variable,
the result of “c” is lower than 20, so the output is “Total was over the limit”.
Keywords and Expressions

• A keyword in Java is one of 57 reserved words with a specific meaning in the language. A keyword
cannot be used as a name for a variable, a method, a class, or any other identifier. For easier
identification, keywords are highlighted in blue throughout the code as syntax highlighting.
Meanwhile, expressions are generated utilizing values, variables, operators, and method calls to
build new value.
• If the integer more than 99, the output will be “You got the high score”.
Statements, Whitespace, and Indentation (Code
Organization)

In a single line, statements include data types, variables, and expressions. The statement will end
with a semicolon (;), which indicates the end of the line to Java. Any white space in the statement
will be ignored by Java, and the program will continue to operate normally as long as the statement
is correct. Java also includes automatic indenting, which helps the user in creating a readable code
structure. White space and indenting are described in the picture.
Code Blocks And The If Then Else Control Statements
Code Blocks And The If Then Else Control Statements

Code blocks in Java are used to designate which section of the code should be
executed. As shown in the diagram, one of the instances of code blocks was utilized
in an if-else statement, which does something if the statement is true and
something else if the statement is wrong.
Methods In Java

• A method is a collection of code that is identified by a name and may be accessed at any time in a
program by referencing the method's name. Methods are a type of subprogram that operates on
data provided by the user and frequently returns a value. A method will require a specific
argument to be defined in order to be used.
Methods in Java
• Syntax in methods:

1. Modifier
• Type of modifier:
• Public → accessible to all classes in your application
• Private → accessible only within the class and its subclasses.
• Protected → accessible within the class.
• Default → accessible within the same class and package.
1. Return type → It might be void if the method returns nothing, or it can be the datatype of the value returned by the method.
2. Method name → The function of a method should normally be represented by its name. It needs to be a lowercase verb. However, if the verb
is more than one word, the method's name is written in camel case. In most cases, an adjective or a noun precedes the method's name to
offer extra specificity. Although method names are distinct, method names used to create polymorphism might sometimes be the same.
3. Parameter list → All of the method's parameters are contained in this list. They are encased in the first brackets (). If there are no parameter,
empty parentheses must be used.
4. Exception list → This list contains the exceptions that the method is capable of throwing. There may be a number of exceptions.
5. Method body → This body is encased with curly braces. The statements inside these brackets run when the method is invoked and return a
value, or no value if it is a void function.
6. Method signature → The method signature is made up of the method name and the argument list. This does not contain the exceptions or the
return type.
More On Methods And A Challenge
Method Overloading

Methods can be overloaded by having the same name


but different parameter or method bodies for two or
more methods.
Session 3
Switch Statement
Switch Statement
• Switch statement in Java is a multi-way branch statement. It makes it
simple to route execution to different areas of code based on the
expression's value. The primitive data types byte, short, char, and int can all
be used in the expression.
• This is how the switch statement works: The expression's value is
compared to each of the case statement's values. The code sequence in the
specific case statement is performed if a match is discovered.
• The default statement will be executed if none of the constants match the
value of the expression. The default statement, on the other hand, is
optional. There is no additional action taken if there are no case matches
and no default is available. The break statement is also used inside the
switch statement to end a run of statements.
For Statement
For Statement
• For statement is an iteration statement that allows the user to
automatically execute the same statement for a set amount of time,
for statement plays a role in creating loops in which a counter variable
is automatically maintained.
• Initialization is the condition under which the loop should begin,
termination is the condition under which the loop should end, and
iteration is the portion of the loop to be executed. As long as the
termination statement is true, the for statement will run.
Methods
Methods in java is a set of code that is identified by a name and may be accessed at any
time in a program by referencing the method's name. Methods are a type of
subprogram that operates on data provided by the user and frequently returns a value.
Function is mentioned in another programming language. In the methods will require a
specific parameter that needed to define it.
Constructor
▪ Constructor is a method of located class which has the same class.

▪ Its goal is to automatically set the initial value of various variables when creating a
class.
▪ One class have multiple constructors with the same name, but different name for the
parameters.
Inheritance
▪ Inheritance refers to the process of transferring attributes from a parent class to a
child class. Connect with one class to other classes.
▪ Have 2 different classes in the figure,“hello” is the parent class, while “grace” is the
child class.
Session 4
Composition & Inheritance
Inheritance
• Inheritance → the child class is extended from the parent class.
• The output of the composition and inheritance are same.
List → Array
• Array is a list in Java. It is indicated by a pair of square brackets after
the datatype modifier. An array's length is immutable, but its
elements are not.
• The element of “array1” is integer, the length of the list was 6.
• The 1st, 3rd, 5th indexes were 10, 15, and 20, respectively.
• If the index is unfilled, the output would be 0 (zero).
Array vs ArrayList
• ArrayList is a variable length Collection class, whereas Array is a fixed
length data structure. The components of the Java ArrayList class are
stored in a dynamic array. It is like an array, but there is no size limit.
ArrayList will automatically resize when you add more elements than
its capacity.
• An array is a data structure with a constant length. ArrayList is a data
structure with a changeable length. It can resize itself if necessary.
When directly or indirectly initializing an array, it is required to
indicate the size of the array.
Differences Between Array and ArrayList
• In principle, an Array is a fundamental Java feature. In Java, an
ArrayList is a collection architecture. As a result, show persons are
gotten to using [], whereas ArrayList contains a variety of methods for
getting to and adjusting components.
Array vs ArrayList (code)
• There are basically two ways to create Array in Java:
• Java Array
• int arr[] = new int[10]
• ArrayList Java
• ArrayList<Type> arrL = new ArrayList<Type>();
Array (left) vs ArrayList (right)
Linked List
• The LinkedList class, like the ArrayList, is a collection that may hold
numerous items of the same type. Because they both implement the
List interface, the LinkedList and ArrayList classes have the identical
methods.
• The elements in the LinkedList are organized into "containers." Each
container has a link to the next container in the list, and the list
includes a connection to the first container. To add an element to the
list, it is placed in a new container, which is then linked to one of the
other containers in the list.
• For storing and accessing data, use an ArrayList, and for manipulating
data, use a LinkedList.
Linked List
• “addFirst()” is used to add an item to the beginning of the list.
Polymorphism & Encapsulation
• Polymorphism, which means "many forms," happens when there are many
classes that are connected via inheritance. We may inherit properties and
methods from another class via inheritance. Polymorphism use these
techniques for a variety of purposes. This enables us to carry out a single
activity in a variety of ways.
• Encapsulation is one of the OOP concepts in the Java programming
language, this concept has a mechanism to remove a data/variable, the
data cannot be accessed by other classes, using the Encapsulation concept,
all data must be set to private, so that other classes cannot access it.
• For example, a superclass is called HP that has a method called
handphone(). The subclasses of HP could be HP1, HP2, and HP3.
Polymorphism & Encapsulation
INTERFACE
• Interface in java is similar with class. It can only include method signatures and
fields, with the goal of standardizing the method for future use.
• An interface in intellij is identified by a green logo next to its name. Furthermore,
the interface implementation class must contain all of the interface's commands,
even the useless ones.
• The interface in the picture (slide 39) is antarmuka → denoted by the green logo
of the icon (beside the name of interface).
• The interface implementation class must contain all of the interface's commands,
even the useless ones.
• Antarmuka interface was implemented in display class. “Hasil” and “ekspresi” are
the objects.
• “a” after “display” is the variable.
• Main class connect to antarmuka interface and display class.
INTERFACE

OUTPUT
Inner class
• It is also possible to nest classes in Java (a
class within a class). Nested classes are
used to arrange classes that belong
together, making your code easier to
understand and maintain. There are 4
(four) types of inner classes: static nested
class, non-static nested class, local class,
and anonymous class.
• To get to the inner class, first make an
outer class object, then make an inner
class object.
Inner class
• It is also possible to nest classes in Java (a class within a class). Nested
classes are used to arrange classes that belong together, making your code
easier to understand and maintain. There are 4 (four) types of inner
classes: static nested class, non-static nested class, local class, and
anonymous class.
• To get to the inner class, first make an outer class object, then make an
inner class object.
• There are 4 type of inner class:
• Nested Inner class → can access the outer class's private variables.
• Method local inner classes → outer class method contains the inner class.
• Anonymous inner classes → has no name at all and written outside the scope of the
outer class.
• Static nested classes
Session 5
GENERICS
• In java, Generics is a technique that
allows the users to build classes for
methods that take into account the
type of the parameter. This is
important for detecting probable
errors and bugs in the code before it
is executed.
• Example: Array list, linked list, etc.
• The IDE instantly reported an error
prior to the code execution by
defining the Java generics, which
was <integer>.
NAMING CONVENTION AND PACKAGES
• Important for programmers to make sure the reability of the code. Includes: packages, classes,
interfaces, methods, constants, variables, and type parameters.
• Package → lowercase and unique (ex: java.Session4, com.Javasession3,
com.sun.java.jag.scrabble, etc.).
• Classes → should be CamelCase and represent the class purpose (ex: ArrayList, DisplayName,
PrintList, MyValue, etc.).
• Interfaces → using CamelCase and programmers often use “I” letter in the front of names (ex:
Antarmuka, ITelephone, etc.).
• Methods → it is more free in terms of the letter case rules (can use mixed case) and represent
the class purpose (ex: getName(), getValue(), addValue(), etc).
• Constants → using uppercase with underscore instead of space (ex: P= 2πR, MAX=12,
PRICE=432.78, etc).
• Variables → using mixed case which start with lowercase and should not use underscores (ex:
myValue, myGrade, etc).
• Type parameters → using a single character with capital letters. For example: E – Element, K –
Key, N – Number, T – Type, V – Value, etc).
PACKAGES
• Packages in Java are a methods of grouping similar classes and interfaces together,
allowing users to utilize classes with the same name in the same project or even the
same class. Java packages may be utilized by calling the "import" method and then
supplying the appropriate package name in the IDE's code block.
• Scope → The visibility of a class, member, or variable is defined by its scope. One
variable in Java can refer to all of the declared variables in a class. This is referred to as
the variable scope.
ACCESS MODIFIER
• Access modifier are the restriction of the accessing to specific class or commands.
• There are 4 types of access modifier,which are default,private,protected,and public.
• Default → same class,same package subclass,and same package non-subclass.
• Private → same class.
• Protected → same class, same package subclass, same package non-subclass, and
different package subclass.
• Public →same class, same package subclass, same package non-subclass, different package
subclass,and different package non-subclass.
STATIC STATEMENTS

• Static statements in Java are separated into the following categories:


static variables (e.g. static int count;), static methods (e.g. static void
foo() ), static block (e.g. static), static inner class (e.g. static class
InnerStatic), and interface static methods (for Java 8 and later).
FINAL STATEMENTS
• Final statements are utilized to impose a constraint on the users. There
are 3 types of usage of final statements:
1. As a variable → to finalize the certain variable’s value, it means that
the user making it a constant.
2. As a method → to restrict the specific method’s overriding.
3. As a class → to restrict the specific class’ extension.
COLLECTION

• The collection framework is a Java architecture for storing and manipulating collections of objects. It is
hoped that diverse collections, including those that may be developed in the future, would have strong
interoperability. Interfaces, aggregate operation, implementation, and algorithms are the five key
components of the collection framework. Java interfaces, in particular, will describe all essential actions
for diverse collection kinds.
• Ordered
• Unordered
• Comparable and comparator are two Java interfaces that may be used to sort Collection objects. Both of these
function in the same way as a binary search. For instance, suppose we had a list of numbers ranging from 0 to
10. The software will compare the value with the middle element, which is three, if we wish to find “7.” Because
“7” is greater than “5,” the software will look for values bigger than three, which it will find in this case. The two
interfaces vary in that I Comparable must be implemented within a class, whereas Comparator is a distinct class,
and (ii) Comparable considers natural ordering, but Comparator can be used for a variety of characteristics.
HIERARCY OF JAVA COLLECTION FRAMEWORK
JAVA CO L L EC T I O N
Session 6
Comparable and Comparator

• Comparable and comparator are two Java interfaces that may be used to sort
Collection objects.
• Both of these function in the same way as a binary search. For instance, suppose
we had a list of numbers ranging from 0 to 10. The software will compare the
value with the middle element, which is 5, if we wish to find “7.” Because “7” is
greater than “5,” the software will look for values bigger than 5.
• The two interfaces vary in that:
1. Comparable must be implemented within a class, whereas Comparator is a
distinct class, and
2. Comparable considers natural ordering, but Comparator can be used for a
variety of characteristics.
Comparable and Comparator
Comparable and Comparator
Comparable and Comparator
Slide 53:
• Comparator was formed outside of other classes, but Comparable was built within
the Seat class.
• Both techniques were employed to sort the seats in this example; however, the
Comparable sorted by seat name, while the Comparator sorted by price.
• Several built-in Collection methods were utilized in addition to the interfaces which
are shuffle, reverse, max, and min.
Slide 54:
• “Theater” object was created in Main code. In addition to the original seats, a new
seat (A00) was added to the list with its own price. The seats within the theater
were then sorted using Comparator PRICE ORDER depending on their costs.
• The order was then reversed and shuffled, respectively, using reverse and shuffle
techniques.
• sortList function is used to order the list which is used fot the comparable interface.
Comparable and Comparator
Maps
• Map is a Java interface that works
like a dictionary, mapping keys to
values. Unlike a dictionary, where a
single key (e.g., a word) can have
numerous values (e.g., definitions), a
Map Class’ key can only have one
value.
• The HashMap class is a simple
dictionary that has been created,
and 3 key-values pairs were inputted
into a dictionary.
• When another value is entered into
an available key, the new value
overwrites the old one. To prevent
this, we can create a simple function,
if the key already has a certain value,
the sentence "Java is entered" will
be printed instead. Finally, the
available pairs are printed.
Set & Hashset
• An unordered list with no duplicates is called a set. HashSet, which employs
hashes to store the elements, is the best-performing implementation of a set.
• Hashing algorithm is an important data structure designed to use a special
function called hash function which is used to index and retrieve items in the
database and map specific values with specific keys for faster element access.
The efficiency of the mapping depends on the efficiency of the hash function
used.
• Hash function takes in data at a fixed-length. These blocks are called ‘data
blocks. The size of the data block differs from one algorithm to another. So, if
the message is exactly of 512-bit length, the hash function runs only once.
Similarly, if the message is 1024-bit, it’s divided into two blocks of 512-bit and
the hash function is run twice. However, 99% of the time, the message won’t be
in the multiples of 512-bit. Using a padding technique, the entire message is
divided into fixed-size data blocks. The hash function is repeated as many times
as the number of data blocks. The output of the first data block is fed as input
along with the second data block. If you change one bit anywhere in the
message, the entire hash value changes.
Set & Hashset
Hashing Algorithm
• Hashing algorithm is an important data
structure designed to use a special
function called hash function which is
used to index and retrieve items in the
database and map specific values with
specific keys for faster element access.
The efficiency of the mapping depends on
the efficiency of the hash function used.
Symmetric and Assymetric Differences of Sets

• Asymmetric and assymetric disparities imply the things that are not
shared (i.e. unique) between sets. Assymetric means that each set has the
same number of unique members, whereas symmetric means that the
number of unique members varies. This is likewise true for Sets in Java.
• In slide 62, two HashSets objects are used to build squares and cubes.
Square stores a square of numbers ranging from 0 to 100, whereas cube
stores cubes with the same range of integers. The getSize method is used
to determine the size of each Set. The addAll and retainAll methods, on
the other hand, are used to extract differences and similarities between
Sets where elements intersect.
Size, intersection, and union of squares and
cubes sets
Sorted Collections and Concluding Remark
• Sets and Maps are interfaces that are not in any particular order. In fact,
there are LinkedHashSet, LinkedHashMap, SortedMap, and SortedSet
versions of these. The first two would keep the elements in their original
order, while the latter two would sort them alphabetically. In TreeSet and
TreeMap, SortedSet and SortedMap were implemented, respectively.
Example codes are not provided because the implementations are
equivalent to the Set and Map interfaces (save for the ordering).
• Furthermore, when using the Collections interface, one thing to keep in
mind is the security of the Objects themselves. Certain things are
designed to be left alone at times (e.g. list of planets in the solar system,
points of the compass, etc.). Several options, such as defining an
immutable Class, unmodifiable Maps, and so on, can be used to prevent
unwanted changes.
Session 7
JavaFX
• JavaFX is a Java library used to build Rich Internet Applications, also a set
Application Programming Interface (API) that can be used to build
interfaces in Java. Applications developed using JavaFX can run on various
devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc.
• To develop GUI Applications using the Java programming language,
programmers rely on libraries such as the Advanced Windowing Toolkit and
Swings. After the advent of JavaFX, Java programmers can now develop
GUI applications with a lot of content. Using Java technology, this
application has a browser penetration rate of 76%.
• To open JavaFX, need to open IntelliJ --> Create New Project --> JavaFX -->
Choose the Java version --> Next --> Choose the Project’s Name --> Finish.
Scene Builder
• Scene Builder is a standalone tool that allows you to generate
interactive FXML files. It can, however, be used in conjunction with
JavaFX. By going to Setting --> Languages and Framework --> JavaFX -->
SceneBuilder.exe, you can accomplish this. After that, the Scene Builder
tab should appear beneath the sample.fxml file in the JavaFX project.
We would notice three main regions if we clicked.
Lamda Expression
• Lambda expression is a short block of code that takes in input and
outputs a value. Lambda expressions are similar to methods, except they
don't require a name and can be used directly within a method's body.
• To print every item in the list, use a lamba expression in the ArrayList's
forEach() method:
Regular Expression (RegEx)
• Regular Expression (RegEx) is a character sequence that generates a search
pattern. This search pattern can be used to define what you're looking for
when searching for data in a text. A regular expression might be as simple
as a single character or as complex as a complex pattern. All forms of text
search and text replace operations can be performed with regular
expressions. Although Java lacks a built-in Regular Expression class, we can
deal with regular expressions by importing the java.util.regex library. The
following classes are included in the package:
• Pattern Class - Pattern's definition (to be used in a search)
• Matcher Class - This class is used to look for a pattern.
• PatternSyntaxException Class - Indicates a regular expression pattern
syntax mistake.
Regular Expression (RegEx)

The output of the picture is “Match found”.


Debugging and Unit Testing
• Debugging in Java is defined as observing source code execute. During
debugging, the user can define a breakpoint in the source code where
the execution should halt. This can be used to look at the variables,
change their content, and so on. To begin debugging the code, right-
click the main method and select Debug As --> Java Application from
the context menu.
Example of Java Project
Guessing
Number Game
Guessing Number Game
Explanation:
- The system will ask the users about the number that range from 1 to 100.
- The game will end if the users answer correctly.
- “nomormesin” is used to generate the random number.
- “jawaban” is used to store the users’ answer.
- The correct answer is printed using “System.out.println” command.
- If the answer is below than 100, the system will give the message that the users answer
correctly.
- If the users answer the number more than 100, the system will give a message that the
number is too high.
- If the users answer other than number, the system will refuse the respond, it means that
error.
ATM Machine
ATM Machine (Output)
ATM Machine (explanation)
• The application is about ATM machine login form.
• If the users enter their card number and PIN correctly, the system will
direct to the next step, the output will be “Berhasil Login”.
• If the users wrong to enter their card number and PIN, the system will
refuse it, the output will be “Gagal Login”.
Thank You

You might also like