1. Trang chủ
  2. » Công Nghệ Thông Tin

Java for beginners the complete guide to learning java for beginners

101 85 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 101
Dung lượng 491,48 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

It should print “Hello World” once executed: public class OurFirstProgram{ public static void mainString args[]{ System.out.println"Hello World"; } } Open your text editor like Notepad a

Trang 2

J AVA FOR B EGINNERS

T HE C OMPLETE G UIDE T O L EARNING J AVA FOR B EGINNERS

Bruce Berke

© 2018

Trang 3

Copyright 2018 by Bruce Berke - All rights reserved.

This document is geared towards providing exact and reliable information in regards to the topic andissue covered The publication is sold with the idea that the publisher is not required to renderaccounting, officially permitted, or otherwise, qualified services If advice is necessary, legal orprofessional, a practiced individual in the profession should be ordered

- From a Declaration of Principles which was accepted and approved equally by a Committee of theAmerican Bar Association and a Committee of Publishers and Associations

In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronicmeans or in printed format Recording of this publication is strictly prohibited and any storage of thisdocument is not allowed unless with written permission from the publisher All rights reserved

The information provided herein is stated to be truthful and consistent, in that any liability, in terms ofinattention or otherwise, by any usage or abuse of any policies, processes, or directions containedwithin is the solitary and utter responsibility of the recipient reader Under no circumstances will anylegal responsibility or blame be held against the publisher for any reparation, damages, or monetaryloss due to the information herein, either directly or indirectly

Respective authors own all copyrights not held by the publisher

The information herein is offered for informational purposes solely, and is universal as so Thepresentation of the information is without contract or any type of guarantee assurance

The trademarks that are used are without any consent, and the publication of the trademark is withoutpermission or backing by the trademark owner All trademarks and brands within this book are forclarifying purposes only and are the owned by the owners themselves, not affiliated with thisdocument

Trang 4

Table of Contents

Introduction

Chapter 1: Getting Started with java

Chapter 2: Java Variables

Chapter 3: Java operators

Chapter 4: Java arrays

Chapter 5: Decision making

Chapter 16- Method Calls

Chapter 17- Java Applets

Conclusion

Trang 5

I NTRODUCTION

Java is a wide programming language, packed with lots of features good for application development.It’s a good coding language for the design/development of desktop apps These are popular as

standalone applications If you need a distributed application, Java is the best language to use Java

applets can be embedded/added on web pages The many features offered by Java have made it apopular coding language Its wide features make it applicable in the development of apps applicable

in various industries To code in Java, you should get the Java compiler Java is compiled, not

interpreted You need an editor in which you can write your Java codes Notepad is good for this.With these, you can start writing and running your Java codes This means it’s easy to get started withJava, making Java a good language for beginners The Java bytecode, normally generated after

compiling Java source codes, is platform-independent, meaning it can be run on any platform

including Windows, Solaris, Linux, etc Java apps are secured via public-key cryptography, makingthem safe/secure Java apps can be linked to various database management systems, for example,MySQL, Oracle, SQL Server, etc This book is an excellent guide on Java programming Get it andknow every aspect of Java and transition from Java Beginner to Java Expert!

Trang 6

C HAPTER 1: G ETTING S TARTED WITH JAVA

Java is a platform as well as a coding language It is a robust, high-level, object-oriented andsecured programming language It was released in 1995 by the Sun Microsystems Java treats

everything as an object Its object model makes it easy to extend The language is compiled, meaningthat we have a Java compiler Java is also platform independent After compiling your Java sourcecode, you get the byte code which can be executed on any platform Java is also well known for beingeasy to learn If you know some basic concepts about object-oriented programming, it will be easyfor you to learn Java It is packed with numerous features, making it widely functional

Authentication in Java is done using a public-key encryption, making its systems very secure This isthe reason we can develop temper-free and virus-free systems with Java In Java, errors are

identified during the compile time, meaning that you cannot go to the run phase without first sortingout the error

Trang 7

ENVIRONMENT SETUP

For you to write and run Java programs, you need a text editor and the Java compiler The Java

compiler comes with the JDK (Java Development Kit) which can be downloaded and installed forfree You also need to have a text editor where you will be writing your Java programs You can evenuse a basic text editor like Notepad and it will be okay However, there are advanced text editors forJava such as Eclipse and Netbeans

First, download and install the JDK on your computer After that, you will have installed Java onyour machine Open your browser then type or paste the following URL:

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

From there, you can get the latest version of the JDK You will then have to set the environment

variables to know the right Java installation directories This means you should set the path variable

Mostly, the installation is done in the c:\Program Files\java\jdk directory To set the path on

Windows, correctly “My Computer”, choose “Properties”, open the “Advanced” tab then choose

“Environment variables” Add the “c:\Program Files\java\jdk\bin” path For Linux users, read thedocumentation of your shell

Trang 9

FIRST PROGRAM

This is our first Java program It should print “Hello World” once executed:

public class OurFirstProgram{

public static void main(String args[]){

System.out.println("Hello World");

}

}

Open your text editor like Notepad and create a new file named “FirstProgram.java Save the file

The java extension marks the file as a Java file Type the above program code in the file and save the

changes Open the command prompt then navigate to the directory in which you have saved the file.Run the commands given below from that directory:

javac FirstProgram.java

java FirstProgram

In my case, I saved the file on the desktop I executed the commands as follows:

Trang 10

The program prints “Hello World” as the result In the command “javac FirstProgram.java”, we are

invoking the java compiler (javac) to compile the program The command returned nothing on thecommand prompt since the program has no error, and no warning was generated The command

generates a class file (FirstProgram.class) in the directory; please confirm In the command “java FirstProgram”, we are simply running the program to give us the result.

Consider the following line extracted from the code:

public class FirstProgram{

The line simply declares a class named FirstProgram Java is a case sensitive language, hence this

class must always be referred to as it is written above The “public” keyword declares that class aspublic, meaning it is accessible from any other class within the same package The { declares thebeginning of the class body, and it should be closed by a }

Note: The filename in which we write the program should match the class-name; otherwise, you will experience trouble when running the program In our case, the class was named

“FirstProgram”, hence the filename should be FirstProgram.java.

Consider the following line extracted from the code:

public static void main(String args[]){

That’s the main method A java program cannot be executed or run without this method Consider the

following line extracted from the code:

System.out.println("Hello World");

We are simply invoking or calling the “println” method to print the text Hello World on the terminal

of the command prompt

Lastly, we have two closing curly braces, }} The first one closes the opening brace for the mainmethod while the second one closes the opening brace for the class

Trang 11

C HAPTER 2: J AVA V ARIABLES

A variable can be seen as a container responsible for holding a value during the life of a program

Each variable is of a certain data type, designative the kind of value that it can hold There are two

steps in using Java variables, that is, variable declaration and variable initialization

Trang 12

The int, float, double and char are the data types, specifying the type of value each variable can or

should hold To declare several variables in one line, separate them using a comma (,) as in the firstexample A variable declaration should end with a semicolon (;)

Trang 15

LOCAL VARIABLES

These are variables declared within a method body They can only be accessed from within thatmethod

Trang 16

INSTANCE VARIABLES

These are the variables that have been defined without the use of STATIC keyword These variablesare specific to an object

Trang 17

int i = 10; //an instance variable

static int b = 2; //a static variable

Trang 18

DATA TYPES

In Java, a data type can be either primitive or non-primitive

PRIMITIVE DATA TYPES

These are the predefined data types that are already provided by Java They are 8 in number including

byte, short, long, char, int, float, Boolean and double data types.

NON-PRIMITIVE DATA TYPES

These are defined by the use of defined class constructors They help programmers access objects.The example given below demonstrates the use of variables:

public class VariableAddition{

public static void main(String[] args){

Trang 19

TYPE CASTING AND TYPE CONVERSION

It is possible for a variable of a particular type to get a value of some other type Type conversion iswhen a variable of a smaller capacity is assigned a variable of a bigger capacity Example:

public class TypecastingExample{

public static void main(String[] args){

Trang 20

C HAPTER 3: J AVA OPERATORS

Operators are symbols used to perform operations For example, the + symbol is used for arithmeticoperations Java supports different operators:

Trang 21

UNARY OPERATOR

This is an operator that takes one operand They increment/decrement a value They include ++(increment) and - -(decrement) Example:

public class UnaryOperatorExample{

public static void main(String args[]){

The program will print 0, 2, 2, 0 The j++ means that the value of j is read first before the increment

is done, hence we got the value of j as 0 If it was ++j, then we would get a 1 as the first value of j.You can try it

Trang 22

ARITHMETIC OPERATORS

These operators are used for performing mathematical operations like multiplication, addition,

division, subtraction etc They are used as mathematical operators Example:

public class JavaArithmeticOperatorsExample{

public static void main(String args[]){

Trang 23

LOGICAL OPERATORS

These operators are used together with the binary values They help in evaluation of conditions inloops and conditional statements They include ||, &&, ! Suppose we have two Boolean variables, a1and a2, the following conditions apply:

a1&&a2 will return true if both a1 and a2 are true; otherwise, they will return false

a1||a2 will return false if both a1 and a2 are false; otherwise, they will return true

!a1 will return opposite of a1

Example:

public class LogicalOperatorExample {

public static void main(String args[]) {

boolean a1 = true;

boolean a2 = false;

System.out.println("a1 && a2: " + (a1&&a2));

System.out.println("a1 || a2: " + (a1||a2));

System.out.println("!(a1 && a2): " + !(a1&&a2));

}

}

The program will return false, true, true

Trang 24

COMPARISON OPERATORS

Java supports 6 types of comparison operators, ==, !=, <, >, >=, <=:

== will return true if both the left and right sides are equal

!= will return true if the left and right sides of the operator are not equal

Returns true if the left side is greater than the right side

< returns true if the left side is less than the right side

>= returns true if the left side is greater than/equal to the right

<= returns true if the left side is less than the right side

Example:

public class JavaRelationalOperatorExample {

public static void main(String args[]) {

Trang 26

C HAPTER 4: J AVA ARRAYS

Arrays are storage structures used for storing same-type elements An array has a fixed size, whichcannot be increased after definition The first element in an array is at index 0

Trang 27

SINGLE DIMENSIONAL ARRAYS

These are arrays in which the elements are stored linearly The declaration of an array takes thesyntax given below:

public class JavaArrayExample{

public static void main(String args[]){

int array1[] = new int[8];

Trang 28

}

}

The array will print the elements contained at different indices You will also get the array length,which is 8

Trang 29

MULTI-DIMENSIONAL ARRAYS

These can be seen as arrays of other arrays In multi-dimensional array declaration, you only addanother set of square brackets to define the other index Example:

int array2[ ][ ] = new int[6][10] ;

You have the authority to control the length of your multi-dimensional array Example:

public class JavaArrayExample2 {

public static void main(String[] args) {

// Creating a 2-dimensional array.

int[][] array2 = new int[6][8];

// Assign only three elements

Trang 30

C HAPTER 5: D ECISION MAKING

In Java, decision making helps us evaluate conditions and run statements based on the outcome of thecondition Let us discuss the statements for decision making:

Trang 31

public class JavaIfStatement {

public static void main(String args[]) {

Trang 32

public class JavaIfElseStatement {

public static void main(String args[]) {

The first statement will be printed, that is, The marks is below 50 This is because the Boolean

expression will be true If it is false, the other statement will be printed Example:

public class JavaIfElseStatement {

public static void main(String args[]) {

Trang 33

} } }

Trang 34

IF ELSE IF ELSE STATEMENT

If you have several conditions to evaluate, use this statement Syntax:

public class JavaIfElseIfStatement {

public static void main(String args[]) {

Trang 35

public class NestingExample {

public static void main(String args[]) {

If the first condition becomes true, the second condition will evaluate This is true in our case, hence

the println statement will be executed If any of the conditions is false, then the println statement

will not be executed

Trang 36

SWITCH STATEMENT

This statement allows us to test a certain variable for equality against some values list Every value

is referred to as case The following syntax is used:

public class JavaSwitchStatement {

public static void main(String args[]) {

Trang 38

C HAPTER 6: LOOPING

Java loops help us do some tasks repeatedly Loops execute the statements in a sequential manner.The first one is run first, followed by the second, etc Let us discuss the Java loops:

Trang 39

public class ForLoopDemo {

public static void main(String args[]){

for(int ix=0; ix<10; ix++){

System.out.println("The ix value is currently: "+ix);

Trang 40

WHILE LOOP

This loop executes the statement(s) as long as the specified condition is true The condition is firstevaluated, and if true, the loop statement(s) are executed If the condition becomes false, the controlwill jump to execute statements that come after the loop It is recommended you add an

increment/decrement to the loop and a test condition so that the loop halts execution when the

condition becomes false Otherwise, the loop may run indefinitely Syntax:

while(A_boolean_expression) {

// Statement(s)

}

Example:

public class JavaWhileLoop {

public static void main(String args[]) {

reached 24, it will check and find the value of xy is 25 The execution of the loop then halts

immediately since continuing to execute it will violate the loop condition

Ngày đăng: 05/03/2019, 08:49

TỪ KHÓA LIÊN QUAN