Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

JAVA PROGRAMMING VOL.

1
[Document subtitle]
4th January 2020

1. WELCOME TO JAVA!

1.1. History of Java

 1972
Dennis Ritchie at AT&T Bell Labs developed the C programming language.

 1986
Bjarne Stroustrup at AT&T Bell Labs developed C++ that supported object-oriented
programming (OOP).

 1995
It was exactly on May 23rd that Sun Microsystems released the first official version
of Java programming language that is considered as an improvement of C++. This
general-purpose software enables you to build and explore databases, write
windowed applications and control handheld devices, among others. Just after five years, Java already had 2.5
million developers worldwide.

Currently is one of the most popular programming languages in use. It can be used to develop applications for a
large variety of environments, such as applications for desktop, web and even mobile devices (eg: media
players, antivirus programs, Web Applications, Enterprise Applications such as banking).One of the main
features of Java is that it is platform independent. This means that a program written in Java can be executed on
any operating system (such as Windows, Mac or Linux). - Their motto is: Write once, run anywhere.

1.2. Java as a Structural Language

Before discussing the particulars, it is useful to think of a computer program in terms of both
its structure and its meaning simultaneously.
A Java program is structured in a specific and particular manner. Java is a language and therefore has a
grammar similar to a spoken language like English. The grammar of computer languages is usually much,
much simpler than spoken languages but comes with the disadvantage of having stricter rules. Applying this
structure or grammar to the language is what allows the computer to understand the program and what it is
supposed to do.

The overall program has a structure, but it is also important to understand the purpose of part of
that structure. By analogy, a textbook can be split into sections, chapters, paragraphs, sentences, and words
(the structure), but it is also necessary to understand the overall meaning of the words, the sentences, and
chapters to fully understand the content of the textbook. You can think of this as the semantics of the program.

pg. 1
1.3. Features of Java

 Object Oriented
In Java, everything is an object. Java can be effectively stretched out and extended to unimaginable dimensions
since it is focused around the Object model.
 Independent of the platform
Dissimilar to numerous other programming dialects including C and C++, when Java is aggregated, it is not
converted into a form, which is particular to any machine. Instead, it is converted into a machine-independent
byte code. This byte code is conveyed over the web and deciphered by Virtual Machines or JVM on whichever
stage it is generally run.
 Simple
Java is intended to be not difficult to learn. In the event that you comprehend the essential idea of OOP, Java
would not be difficult to ace.
 Secure
With Java’s security framework, it empowers to create frameworks, which are free of viruses and tampering.
Public-key encryption is used as the core authentication strategy.
 Independent of Machine Architecture
Java compiler produces an object file format, which is independent of the architecture of the machine. The
assembled code can be executed on numerous processors, with the single requirement that they must all have
Java runtime framework.
 Portability
The fact that Java code is machine and platform independent makes it extremely compact. Compiler in Java is
composed in ANSI C with a clean convey ability limit, which is a POSIX subset.
 Robustness
Java tries to kill circumstances, which can lead to potential system failures, by stressing chiefly on runtime
checking and compile time checking.

 Support for Multithreaded Applications


With Java’s multithreaded feature, it is conceivable to compose programs that can-do numerous assignments at
the same time. This configuration gimmick permits designers to build easily running intelligent applications.
 Interpreted Code
Java byte code is interpreted on the fly to local machine. The advancement methodology is quicker and more
expository since the interfacing is an incremental and lightweight process.
 High Performance
With the utilization of Just-In-Time compilers, Java enhances the performance of the system.

pg. 2
 Distributed
Java is intended for the conveyed environment of the web.
 Dynamic
Java is thought to be more dynamic than C or C++ since it is intended to adjust to an advancing environment.
Java projects can convey broad measure of run-time data that can be utilized to check for accesses and respond
to the same on run-time.

2. THE FIRST JAVA PROGRAM

2.1. Basic Java Syntax (you can see another explanation Java…step-by-step, page 39)

A basic Java program can be broken down into several constructs and elements. Typically, it can be
characterized as a collection of objects, which communicate with each other by calling each other’s routines.
The basic definitions of objects and classes are given below:
Class
A class can be described as a blueprint that portrays the practices/expresses all the behaviors and states of its
objects.
Object
Objects are characterized by two components namely, methods and attributes or variables. For instance, if you
consider the example of a puppy, then it has the following attributes or states: name, color and breed. In
addition, it also has the following behaviors, which include woofing, wagging and consuming. Any object is
nothing but an instance of a class.
Instance Variables
Each object has its set of variables. An object’s state is made by the qualities allotted to these variables during
program execution.
Methods
A method is the definition of a method. Moreover, a class can contain numerous methods. It is in these methods
that behaviors like where the rationales are composed, information is controlled and all the activities are
executed.

2.2. Hello World!

In Java, every line of code that can actually run needs to be inside a class. In Java, each application has an entry
point, or a starting point, which is a method called main.

pg. 3
Example: Create a program that prints “Hello World!” to the screen.

2.3. System.out.println()

There are 3 kinds of print statements:


 Print
Example1: Create a program using print to output “Hello World”
 Println
Example2: Create a program using println to output “Hello World”
 Printtf
Gives more control over how things are printed.

5th January 2020

3. PARTS OF THE JAVA PROGRAM

3.1. Comments

Comments are the descriptive parts of the program that explain what the codes are all about. They are special
sections of text that improve the program’s readability – helping people understand the operation of the
program. Basically, these are the words that we humans read but the compiler totally ignores.
There are two types of comments, depending on how you write them:
1. One-Line or End-of-Line Comment (Single line comment)
Starting with two slashes, this comment text is short enough to fit on one line. It is also written at the end of a
line of code. In the previous simple Java program example, the one line comment that we have is:
Eg: public class Comment{
Public static void main (String [] args){
//Write the text with uppercase
System.out.println(“HI WORLD”);
}

pg. 4
}

2. Block or Multi-Line Comment


This type is characterized by multiple one-line comments (meaning, your comment text is too long to fit in one
line). However, the two slashes are replaced with an opening “/*” at the start of the comment and ends with a
closing “*/” (to save time in writing “//” for every line). Again, the compiler ignores everything between the
two slashes. In the previous simple Java program example, we have:
Eg1: public class Comment{
Public static void main (String [] args){
/*
Use println in order to output the text
Write the text with uppercase
*/
System.out.println(“HI WORLD”);
}
}

3. Documentation comments
Are special comments that have the appearance of multi-line comments with the difference being that they
generate external documentation of your source code.
Eg2: public class Doc{
Public static void main(String [] args){
/**This is a documentation comment */
System.out.println(“Hello”);
}
}

Javadoc is a tool which comes with JDK and it is used for generating Java code documentation in HTML
format from Java source code which has required documentation in a predefined format.
When a documentation comment begins with more than 2 asterisks, Javadoc assumes that you want to create a
“box” around the comment in the source code. It simply ignores the extra asterisks.
Eg3: public class Doc{
Public static void main(String [] args){
pg. 5
/*********************
This is the start of a method
**********************/
System.out.println(“Hello”);
}
}

4.VARIABLES AND OPERATORS IN JAVA

4.1. Variables

Variables are just like containers which hold the values while the program is executed. For instance, suppose
your program needs to store the age of a user. To do that, we can name this data userAge and declare the
variable userAge using the following statement:
int userAge;
This declaration statement first states the data type of the variable, followed by its name. The data type of a
variable refers to the type of data that the variable will store (such as whether it’s a number or a piece of text).
In our example, the data type is int, which refers to integers. The name of our variable is userAge. After you
declare the variable userAge, your program will allocate a certain area of your computer's memory space to
store this data. You can then access and modify this data by referring to it by its name, userAge.
There are three rules to create an identifier:
 Characters from A to Z as well as their lowercase counterparts can be used.
 Numbers from 0-9 can be used.
 Special characters that can be used are $ (the dollar sign) and _ (underscore).

4.2. Primitive data types (table from page 59, Java … step-by-step)

There are eight basic data types that are predefined in Java. These are known as primitive data types. The first 4
data types are for storing integers (i.e. numbers with no fractional parts). They are as follows:

 Byte
The byte data type is used for storing integers from -128 to 127. It uses 1 byte of storage space (this is known as
the width or the size of the data type). We normally use the byte data type if storage space is a concern or if we

pg. 6
are certain the value of the variable will not exceed the -128 to 127 range. For instance, we can use the byte data
type to store the age of a user as it is unlikely that the user’s age will ever exceed 127 years old.

 Short
The short data type uses 2 bytes of storage space and has a range of -32768 to 32767.

 Int
The int data type uses 4 bytes of storage space and has a range of -2^31 (-2147483648) to 2^31-1
(2147483647). It is the most commonly used data type for storing integers as it has the most practical range.

 Long
The long data type uses 8 bytes of storage space and has a range of -2^63 to 2^63-1. It is rarely used unless you
really need to store a very large integer (such as the number of inhabitants on Earth). In order to specify a long
value, you have to add the suffix “L” to the end of the number. We’ll talk more about suffixes in the next
section. In addition to having data types for storing integers, we also have data types for storing floating point
numbers (i.e. numbers with fractional parts). They are:

 Float
The float data type uses 4 bytes of storage and has a range of approximately negative 3.40282347 x 10^38 to
positive 3.40282347 x 10^38. It has a precision of about 7 digits. This means that if you use float to store a
number like 1.23456789 (10 digits), the number will be rounded off to approximately 7 digits (i.e. 1.234568).
You need to add the suffix ‘F’ at the end.

 Double
The double data type uses 8 bytes of storage and has a range of approximately negative 1.79769313486231570
x 10^308 to positive 1.79769313486231570 x 10^308, with a precision of approximately 15 digits. By default,
whenever you specify a floating-point number in Java, it is automatically considered to be a double, not a float.
If you want Java to treat the floating-point number as a float, you have to add a suffix “F” to the end of the
number. Unless memory space is a concern, you should always use a double instead of a float as it is more
precise. Besides the six data types mentioned above, Java has two more primitive data types. They are:

 Char
char stands for character and is used to store single Unicode characters such as ‘A’, ‘%’, ‘@’ and ‘p’ etc. It uses
2 bytes of memory.

 Boolean
Boolean is a special data type that can only hold two values: true and false. It is commonly used in control flow
statements.
Example3: Create a program in which you will use all the primitive data learned + String type
and all that you’ve learned until this point.

pg. 7
4.3. Basic operators

Besides assigning an initial value to a variable or assigning another variable to it, we can also perform the usual
mathematical operations on variables. Basic operators in Java include +, -, *, / and % which represent addition,
subtraction, multiplication, division and modulus respectively.
Eg4:
Suppose x = 7, y = 2
Addition: x + y = 9
Subtraction: x - y = 5
Multiplication: x*y = 14
Division: x/y = 3 (rounds down the answer to the nearest integer)
Modulus: x%y = 1 (gives the remainder when 7 is divided by 2)

! Pay attention to division because we can have two cases:


1. When we have division with integers the result will be an integer
2. When we have division with double or float the result will be accurate.

5.EXERCISES FROM YOUTUBE

Eg1: https://www.youtube.com/watch?v=SCj1WUy2DaU&list=PLnVYEpTNGNtXU7 -
70Zsr4gvayqHg3L5ap&index=8
Eg2: https://www.youtube.com/watch?v=Tb0hDyYBYXY&list=PLnVYEpTNGNtXU7 -
70Zsr4gvayqHg3L5ap&index=15
Eg3: https://www.youtube.com/watch?v=aME5ODq -Rgg&list=PLnVYEpTNGNtXU7-
70Zsr4gvayqHg3L5ap&index=16
Eg4: https://www.youtube.com/watch?v=hYRC5Rg65Xw&list=PLnVYEpTNGNtXU7 -
70Zsr4gvayqHg3L5ap&index=18
Eg5: https://www.youtube.com/watch?v=aME5ODq -Rgg&list=PLnVYEpTNGNtXU7-
70Zsr4gvayqHg3L5ap&index=16
Eg6: https://www.youtube.com/watch?v=hYRC5Rg65Xw&list=PLnVYEpTNGNtXU7 -
70Zsr4gvayqHg3L5ap&index=18

pg. 8
Eg7: https://www.youtube.com/watch?v=snYE74w2mus&list=PLnVYEpTNGNtXU7 -
70Zsr4gvayqHg3L5ap&index=19

11th January 2020

6. FLOW CONTROL

This chapter will emphasize on a non-sequential method of Java programming. You will get acquainted with the
if-then-else and different loop statements. With our previous simple program examples, we were oriented that a
Java class is executed in one direction – from the topmost line of code up to the bottom, or what we call
sequential programming. However, there will be cases that you will be required to write codes in a non-
sequential fashion, especially for those more complicated scenarios. This is accomplished using logical and
looping statements, so you can control the flow of your program to perform more complex functions.

6.1. IF – THEN – ELSE

This is the most basic flow control statement that uses logical operators to determine whether or not a specific
condition is fulfilled.
Example 4: Create a program that will display whether the user is a minor or not based on the
age that he has provided.

6.2. Loops

While loop – Considered as the simplest kind of “event driven” loop, this statement will execute the methods
inside the while block as long as the specific conditions are met. Depending on the conditions set, this loop may
never run even once.
Example 5: Java… step- by- step. page 72

The do…while Loop -The do…while loop is nearly identical to the while loop, but instead of checking
the conditional statement before the loop starts, the do…while loop checks
the conditional statement after the first run, then continuing onto another iteration.
Example 6 : https://www.educative.io/courses/learn -java-from-scratch/YMqlW49VnL9

pg. 9
pg. 10
pg. 11

You might also like