JAVA Crash Course-JAED By Sabihuddin Ahmed Siddiqui

42
Java Crash Course – Java 1 LECTURE CONTENTS Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content Theory Classes: 28 Practical Classes: 9(+3) = 12 By Sabihuddin Ahmed Siddiqui Email: [email protected] Contact: 00923002730073 1 1. Introduction to Java, History History Sun Microsystems designed Java in early 1990s. A small group named “Green Team.” The main creator of Java was James Gosling (a man who gave birth to Java becomes a father) The main aim of Java was, to solve problems of many household machines. No one wanted to use Java project. Hence, remained unsuccessful for some years. The first suggested name of Java was OAK. There was another language used named Oak, and later on OAK, name was changed to Java. OAK name renamed to Java in 1994. Java was released on May 27 th , 1997. It was a public release. Java was focussed on browser based platform. Thus, internet development was become possible. Netscape communicator (Company) was the first applet runner on the browser. Hence, internet was targeted. Now, 5 Billion devices use Java. Enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7. Goals of the Language Based on Object-oriented (true object-oriented) A single program can be executed on multiple platform/operating systems Networked programming was supported comprehensively Code/program can be executed from remote sources securely. Very easy to use. Java and a Typical Java Development Environment The microprocessor revolution’s most important contribution to date is that it made possible the development of personal computers. Microprocessors are having a profound impact in intelligent consumer-electronic devices. Recognizing this, Sun Microsystems in 1991 funded an internal corporate research project led by James Gosling, which resulted in a C++-based object-oriented programming language Sun called Java. A key goal of Java is to be able to write programs that will run on a great variety of computer systems and computer-control devices. This is sometimes called “write once, run anywhere.” The web exploded in popularity in 1993, and Sun saw the potential of using Java to add dynamic content, such as interactivity and animations, to web pages. Java garnered the attention of the business community because of the phenomenal

Transcript of JAVA Crash Course-JAED By Sabihuddin Ahmed Siddiqui

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

1

1. Introduction to Java, History

History

Sun Microsystems designed Java in early 1990s. A small group named “Green Team.”

The main creator of Java was James Gosling (a man who gave birth to Java – becomes a father)

The main aim of Java was, to solve problems of many household machines.

No one wanted to use Java project. Hence, remained unsuccessful for some years.

The first suggested name of Java was OAK.

There was another language used named Oak, and later on OAK, name was changed to Java. OAK name renamed to Java in 1994.

Java was released on May 27th, 1997. It was a public release.

Java was focussed on browser based platform. Thus, internet development was become possible.

Netscape communicator (Company) was the first applet runner on the browser. Hence, internet was targeted.

Now, 5 Billion devices use Java.

Enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.

Goals of the Language

Based on Object-oriented (true object-oriented)

A single program can be executed on multiple platform/operating systems

Networked programming was supported comprehensively

Code/program can be executed from remote sources securely.

Very easy to use.

Java and a Typical Java Development Environment

The microprocessor revolution’s most important contribution to date is that it made

possible the development of personal computers. Microprocessors are having a

profound impact in intelligent consumer-electronic devices. Recognizing this, Sun

Microsystems in 1991 funded an internal corporate research project led by James

Gosling, which resulted in a C++-based object-oriented programming language Sun

called Java.

A key goal of Java is to be able to write programs that will run on a great variety of

computer systems and computer-control devices. This is sometimes called “write

once, run anywhere.”

The web exploded in popularity in 1993, and Sun saw the potential of using Java to

add dynamic content, such as interactivity and animations, to web pages. Java

garnered the attention of the business community because of the phenomenal

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

2

interest in the web. Java is now used to develop large-scale enterprise applications,

to enhance the functionality of web servers (the computers that provide the content

we see in our web browsers), to provide applications for consumer devices (e.g., cell

phones, smartphones, television set-top boxes and more) and for many other

purposes. Sun Microsystems was acquired by Oracle in 2009. At the JavaOne 2010

conference,Oracle announced that 97% of enterprise desktops, three billion

handsets, and 80 million television devices run Java. There are currently over 9

million Java developers, up from 4.5 million in 2005.10 Java is now the most widely

used software development language in the world.

Focusing on Open source In 2006 Sun started to make Java available under the GNU General Public License (GPL). Oracle continues this project called OpenJDK.

Introduction to Java JDK/SDK (SE/ME/EE) The Java Development Kit (JDK) is an implementation of either one of the Java SE, Java EE or Java ME platforms released by Oracle Corporation in the form of a binary product aimed at Java developers on Solaris, Linux, Mac OS X or Windows. Since the introduction of the Java platform, it has been by far the most widely used Software Development Kit (SDK).[citation needed] On 17 November 2006, Sun announced that it would be released under the GNU General Public License (GPL), thus making it free software. This happened in large part on 8 May 2007, when Sun contributed the source code to the OpenJDK. Difference between JDK and SDK: Is there any substantial difference between those two terms? JDK stands for Java Development Kit that is a subset of SDK (Software Development Kit). But specifying Java SDK, it should mean the same as JDK. The JDK is a subset of what is loosely defined as a software development kit (SDK) in the general sense. In the descriptions which accompany their recent releases for Java SE, EE, and ME, Sun acknowledge that under their terminology, the JDK forms the subset of the SDK which is responsible for the writing and running of Java programs. The remainder of the SDK is composed of extra software, such as Application Servers, Debuggers, and Documentation.

Java Runtime Environment

The Java Runtime Environment (JRE), also known as Java Runtime, is part of the Java Development Kit (JDK), a set of programming tools for developing Java applications. The Java Runtime Environment provides the minimum requirements for executing a Java application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files.

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

3

Why use Java? There are three main reasons for using the JAVA programming language over other choices: portability, simplicity of coding, and widespread use; especially in web development. Java is completely portable between different operating systems (Mac, Linux, and Windows). This is because the code you write is only partially finished after it is compiled by the programmer. The rest of the work is performed on the user’s computer using the Java Virtual Machine (JVM). There is a JVM for each major operating system, and after being downloaded and installed by the user, it completes the Java code that the programmer wrote. The JVM adds in commands specific to the operating system it is installed on to make the program run correctly for that operating system. So the JVM for a Macintosh will add in Macintosh specific code and the JVM for Windows will add in Windows specific code. This portability has lead to Java being used widely, especially for the web development industry. Since web based applications run on multiple operating systems it was essential to have a programming language, such as Java, that could run on any operating system. Today Java is everywhere, and is used for most major web applications. Another factor is Java’s increased use is its simplicity of programming in comparison to other languages, especially C++. Java enforces error checking, eliminates pointers, cannot be written without using object oriented design, and prevents bad programming practices by building these functions directly into Java’s grammar. These features make Java a much simpler (and much less error prone) then many other languages that do not have these restrictions.

b. Getting started with Java

About: This course comprises on the basic steps towards software development and engineering with Java.

What is Java?

Object Oriented

Platform independent:

Simple

Secure

Architectural- neutral

Portable

Robust

Multi-threaded

Interpreted

High Performance

Distributed

Dynamic

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

4

Similarities with other languages

Syntax comparison with C/C++ and Java

Class

Methods/Functions

Keywords

Loops

Conditions

Format Specifiers

Escape Sequence

Dialogs

Exceptions

Comparison of Java with C#

After Java released, Microsoft developed C#, which is closely related to Java.

Some features of C# are parallel to Java. Both Java & C# share the C++ style, syntax, distributed programming, and utilize the object Modelling.

Overall C# is somehow similar to Java with some differences.

If you know Java or C#, the learning process will be easy for Java and vice versa.

Basically, C# and Java are two different optimized programming environment.

Java and C# are developed on C++.

Both the languages Java & C# are cross platform independent, capable of portable program code.

Editors & IDE (Interactive Development Environment)

Command line (use of java compiler “javac filename.java”, java player “java filename.class.”-Bytecode

Text editors

Eclipse

NetBeans

Download Eclipse or NetBeans

Eclipse: http://www.eclipse.org Eclipse is a flexible and extensible IDE platform. Firstly developed by IBM and now is an open source. It can be downloaded from Eclipse Foundation that is http://www.eclipse.org. Eclipse was written in Java, it also needs JRE (Java Runtime Environment) to work. Therefore, it runs on large range of platforms. It comes with Java Development Tools(JDT), by default. It has extensions and additional tools to help ensure the development of programs in other languages as well. JRE is flexible and it can even be used as a framework for the development for applications unrelated to IDEs.

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

5

NetBeans: http://www.netbeans.org NetBeans, another powerful IDE. It was originally developed and distributed by Sun Microsystems. NetBeans is also an open source, which was declared in 2000 and is supported with plug-ins developed by the open source community.

Installing java with Eclipse and NetBeans or using Notepad editor

Download Eclipse Juno/Galalio or Enterprise Edition (J2EE) Greater than version 3.7

Download NetBeans from Oracle.com or Netbeans.org, version 7.3/4 (JDK-must be greater or equals to JDK 1.6/1.7

Use Notepad.exe editor to write Java file with .java extension

Windows/Mac OS X/Linux

While you download Java from NetBeans or Eclipse make sure which platform you use.

Characteristics

Platform Independence

Object-Oriented

Typed Language (Strong Structure)

Interpreted & Compiled Execution (Language) – JVM, Bytecode

Memory Management (Automatic)

Robustness

JVM:

JVM is an interpreter

JVM is used to take Bytecode as an input and execute it.

While translating Java program into bytecode, that makes it easier to run a program in a variety of environment platform, only the JVM needs to be implemented for each platform

JVM is not platform independent

Once JVM is installed, Java program can be run on it.

JVM varies from platform to platform, and has the capability to understand the same Java Bytecode.

BYTECODE:

Bytecode is non-executable code

Bytecode is optimized for high set of instructions.

Java runtime systems execute Bytecode which is known as JVM

c. Classes and objects

What is an Object? (an object could be anything or a real world entity- An object is an instance of a class. The object is the real element which has data and can perform actions. Each object is created based on the class definition.) Objects: your car, table, dog, your desk, your television set, your bicycle.

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

6

Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming. Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

What is an Instance? (an actual usage of a class is called instance). A synonymous working part as object.

How to create objects? Objects can be created through class instantiation.

Instantiation Just as someone has to build a car from its engineering drawings before you can actually drive a car, you must build an object of a class before a program can perform the tasks that the class’s methods define. The process of doing this is called instantiation. An object is then referred to as an instance of its class.

What is a Class?

A class is a blue print from which separate or individual object/s are created.

A class denotes a category of objects, and acts as a blueprint for creating such objects. A class models an abstraction by defining the properties and behaviors for the objects representing the abstraction.

An object exhibits the properties and behaviors defined by its class.

The properties of an object of a class are also called attributes, and are defined by fields in Java.

A field in a class is a variable which can store a value that represents a particular property of an object.

The behaviors of an object of a class are also known as operations, and are defined using methods in Java.

Fields and methods in a class declaration are collectively called members.

What is OOP? To be object oriented, a language is designed around the concept of objects. that are something, have certain properties and exhibit certain behaviors. This means the language generally includes support for:

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

7

Introduction to Object-oriented Programming (OOP) The object-oriented is a programming paradigm where the program logic and data are weaved, it is a way of conceptualizing a program's data into discrete "things" referred to as objects, each having its own properties and methods. Let's see an example. Suppose your friend is a bank manager and he wants you to help improving their system. The first object you might design is the general-purpose Account. The Account object has properties and methods. For each client your friend's bank have, you would have to create an Account object. Characteristics As follows the most important features of object-oriented programming: • Encapsulation. Capability to hide data and instructions inside an object. • Inheritance. Ability to create one object from another. • Polymorphism. The design of new classes is based on a single class. • Message Passing. It is the way objects communicate with each other. • Garbage Collection. Automatic memory management that destroys objects that are no longer in use by the program. Benefits As follows some benefits of using object-oriented programming: • Re-usability. You can write a program using a previous developed code. • Code Sharing. You are able to standardize the way your are programming with your colleagues. • Rapid Modeling. You can prototype the classes and their interaction through a diagram. Drawbacks As follows the disadvantages of using object-oriented programming: • Size. Are larger than other programs, consuming more memory and disk space. • Effort. Require a lot of work to create, including the diagramming on the planning phase and the coding on the execution phase. Basic Concepts Class Basic template that specifies the properties and behaviours of something (real life or abstract). Object Particular instance of a class that responds consequently to events. Attribute Characteristics of the class. Often called instance variables. Method Algorithm associate to an class that represent a thing that the object does. Subclass Class based on another class.

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

8

Inheritance Process where the subclass gets the attributes and methods from its parent class. Interface Specific template that enforces certain attributes and methods of a class. Package Namespace that organizes a set of related classes and interfaces. Event Alert the application when there is a state change of the object. –Encapsulation

Encapsulation means to create a boundary around an object to separate its external (public) behavior from its internal (private) implementation.

Consumers of an object should only concern themselves with what an object does, not how it does it.

–Inheritance

A class may inherit from a single base class

A class may implement zero or more Interfaces –Polymorphism

A class can be used as its own type, cast to any base types or interface types it implements.

Objects may methods as virtual; virtual methods may be overridden in a derived type. These are executed instead of the base implementation.

OOP vs Non-OOP

OOP: such as Java, C, C#, C++ (object based)

Non-OOP: Embedded applications

OOA & D (Object Oriented Analysis & Design) Object-oriented analysis and design is the method that leads us to an object-oriented decomposition. By applying object-oriented design, we create software that is resilient to change and written with economy of expression. We achieve a greater level of confidence in the correctness of our software through an intelligent separation of its state space. Ultimately, we reduce the risks that are inherent in developing complex software systems.

Class Diagram In software engineering, a class diagram in the Unified Modelling Language is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes and methods.

A Class consists of: a. A unique name, starting with Uppercase letter b. A list of attributes (int, string, double, Boolean)-Use of Data types c. A list of methods(addition(), sub(), Mul() & Div())-User Defined

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

9

Class Name

Attributes

Methods()

Access Modifiers: Public (+), Private(-), Protected(#), Package(~).

ClassName(Book)

-title: string -author: string

(+)setTitle() (+)getTitle() (+)setAuthor() (+)getAuthor() (+)toString()

d. Java Basic Syntax

Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.

Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

Instant Variables - Each object has its unique set of instant variables. An object.s state is created by the values assigned to these instant variables.

e. Class Declaration & Modifiers

Access modifiers: default, public, protected, private.

Non-access modifiers (including strictfp, final, and abstract).

f. Executing/Writing a Java program

Program Execution through JVM

Java program is executed by JVM

JVM prevents Java code from generating side effects outside the system

Security is enhanced by certain restrictions exist in Java

g. Using comments in Java The Java language supports three kinds of comments:

1. /* text */: The compiler ignores everything from /* to */. Block level comment 2. /** documentation */: This indicates a documentation comment (doc comment,

for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. Documentation level comment

3. // text: The compiler ignores everything from // to the end of the line. Single line comment.

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

10

Delimiters Use // Used for commenting a single line /* ————— */ Used for commenting a block of code /** —————*/ Used for commenting a block of code. Used by the Javadoc tool

for generating Java documentation. h. Writing a Java Program. Syntax for a standalone application in Java:

class <classname> { //A

public static void main(String args[]) { //B

Statements (1..n); } //B

}//A

2. Variables and Operators

a. Introduction to Variables The Java programming language defines the following kinds of variables:

Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.

Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field

defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.

Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

Parameters You've already seen examples of parameters, both in the Bicycle class and in the main method of the "Hello World!" application. Recall that the

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

11

signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well.

Variable Type Declaration Example Memory Range / Notes

Byte byte register = 64; (8 bit = -2^8 to 2^8 –1 )

Short Integer short shortInt = 24859; (16 bit = -2^16 to 2^16 -1)

Integer int x = 20; (32 bit = -2^32 to 2^32 -1)

Long Integer longInt = 3; (64 bit = -2^64 to 2^64 -1)

Boolean boolean loopDone = false; 0 or 1

Float float temperature = 34.6; 1.4E-45 to 3.4E+38

Double double speed = 5945.32; 4.9E-324 to 1.7E+308

Final <variable type> final float PI = 3.141592 Same as const in C++

String String lastName = “Koh”; Actually an object.

b. Introduction to Primitive Data Types

Primitive Data Types The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen: int gear = 1; Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are: byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation. short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters. int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

12

use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers. long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. The unsigned long has a minimum value of 0 and maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long. float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform. double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency. boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined. char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). Default Values It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style. The following chart summarizes the default values for the above data types.

Data Type Default Value (for fields)

byte 0

short 0

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

13

int 0

long 0L

float 0.0f

double 0.0d

char '\u0000'

String (or any object) null

boolean false

Legal Identifiers number, Number, sum_$, bingo, $$_100, mal, grub, _MIN, _MAX Illegal Identifiers 48chey, all@hads, gradE-sum Keywords Keywords are reserved words that are predefined in the language and cannot be used to denote other entities. All the keywords are in lowercase, and incorrect usage results in compilation errors. Reserved Literals in Java null true false Reserved Keywords not Currently in Use Const goto Literals Primitive types are special data types built into the language; they are not objects created from a class. A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation. As shown below, it's possible to assign a literal to a variable of a primitive type: boolean result = true; char capitalC = 'C';

abstract default if private this assert do implements protected throw boolean double import public throws break else instanceof return transient byte enum int short try case extends interface static void catch final long strictfp volatile char finally native super while class float new switch continue for package synchronized

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

14

byte b = 100; short s = 10000; int i = 100000; Valid Literals Integer: 2000 0 -7 Floating-point: 3.14 -3.14 .5 0.5 Character: 'a' 'A' '0' ':' '-' ')' Boolean: true false String: "abba" "3.14" "for" "a piece of the action" Escape Sequences Certain escape sequences define special characters. These escape sequences can be single-quoted to define character literals. For example, the character literals '\t' and '\u0009' are equivalent. However, the character literals '\u000a' and '\u000d' should not be used to represent newline and carriage return in the source code. These values are interpreted as line-terminator characters by the compiler, and will cause compile time errors. You should use the escape sequences '\n' and '\r', respectively, for correct interpretation of these characters in the source code.

White Spaces A white space is a sequence of spaces, tabs, form feeds, and line terminator characters in a Java source file. Line terminators can be newline, carriage return, or a carriage return-newline sequence.

c. Formatted Output & in Input int a=19; String a1="a"; using format specifiers(%d,%s,%c) and escape sequence (\n, \r, \b) with use of comma (,) 1 System.out.printf("Message %d\n",a); System.out.printf("This is small letter :%s ", a1);

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

15

2. Without Format Specifiers & Escape Sequence without use of comma(,), but a concatenator a (+) sign. System.out.println("Message: "+a); System.out.println("This is small letter : "+a1);

d. Operators Simple Assignment Operator = Simple assignment operator Arithmetic Operators + Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator / Division operator % Remainder operator Unary Operators + Unary plus operator; indicates positive value (numbers are positive without this, however) - Unary minus operator; negates an expression ++ Increment operator; increments a value by 1 -- Decrement operator; decrements a value by 1 ! Logical complement operator; inverts the value of a boolean Equality and Relational Operators == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to Conditional Operators && Conditional-AND || Conditional-OR ?: Ternary (shorthand for if-then-else statement) Type Comparison Operator instanceof Compares an object to a specified type Bitwise and Bit Shift Operators ~ Unary bitwise complement

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

16

<< Signed left shift >> Signed right shift >>> Unsigned right shift & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR

Category Type Operator-Symbol Flow/Direction

Postfix ( ) [ ] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

e. Type Casting

Casting can be done from one variable type to another variable type by placing the basic type in parentheses next to the variable: int x = 65; char bigA = (char)x; System.out.println(bigA); This produces the output ‘A’ because 65 is the ASCII code for capital a. Casting can also be done from object to object, object to primitive, and primitive to object. Type Conversion • byte short int long (implicitly) • byteshortintlong (Explicit casting) • float double (implicit) • floatdouble (explicit) • boolean(Cannot be casted)

• Types of Casting

Implicit Casting byte c = 120; short d = c;

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

17

Explicit Casting short c = 234; byte d = (byte)c; (You need to explicitly mention type and to cast with)

3. Decision Making and Iterations

a. Algorithms Any computing problem can be solved by executing a series of actions in a specific order. A procedure for solving a problem in terms of 1. the actions to execute and 2. the order in which these actions execute is called an algorithm.

b. Pseudocode Pseudocode is an informal language that helps you develop algorithms without having to worry about the strict details of Java language syntax. The pseudocode we present is particularly useful for developing algorithms that will be converted to structured portions of Java programs. Pseudocode is similar to everyday English—it’s convenient and user friendly, but it’s not an actual computer programming language.

c. Control Structures o Sequence (Statement1..Statement(n)) o Selection (Conditions if..then..else, if..then..else if..else)—Simple & Nested.

Double selection statements o Repetition (Loops: Definite, Indefinite & Nested)—For{}, while(){}, do{};while();

d. Decision Making Statements

The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. This section describes the decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) supported by the Java programming language. The if-then and if-then-else Statements The if-then Statement if (<conditional expression>) <statement> The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. Simple English: Algorithmic/Pseudo Format

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

18

If percentage is greater than or equal to 50 then

Print “Passed” Code Format: if ( Percentage >= 50 ) // You need to place curly brackets { } with every condition. System.out.println( "Passed" ); if ( Percentage >= 50 ) //code in Java { System.out.println( "Passed" ); }

If…else Double-Selection Statement The if single-selection statement performs an indicated action only when the condition is true; otherwise, the action is skipped. The if…else double-selection statement allows you to specify an action to perform when the condition is true and a different action when the condition is false. if (<conditional expression>) <statement1> else <statement2> For example,

If percentage is greater than or equal to 50 Print “Passed”

Else Print “Failed”

Code Format: If ( Percentage >= 60 ){ System.out.println( "Passed" ); } Else { System.out.println( "Failed" );}

Print “Passed” [Percentage>=50]

[Percentage<50]

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

19

if(x==65) { System.out.println("A"); } else { System.out.println("Invalid"); }

Conditional Operator (? : ) Java provides the conditional operator (?:) that can be used in place of an if…else statement. This is Java’s only ternary operator (operator that takes three operands). Together, the operands and the ?: symbol form a conditional expression. The first operand (to the left of the ?) is a boolean expression (i.e., a condition that evaluates to a boolean value—true or false), the second operand (between the ? and :) is the value of the conditional expression if the boolean expression is true and the third operand (to the right of the :) is the value of the conditional expression if the boolean expression evaluates to false. For example,

System.out.println( Percentage >= 50 ? "Passed" : "Failed" ); prints the value of println’s conditional-expression argument. The conditional expression in this statement evaluates to the string "Passed" if the boolean expression student- Grade >= 60 is true and to the string "Failed" if it’s false. Thus, this statement with the conditional operator performs essentially the same function as the if…else statement Nested if…else Statements A program can test multiple cases by placing if…else statements inside other if…else statements to create nested if…else statements. A nested if…else that prints A for exam percentages greater than or equal to 90, B for percentages 85 to 89, C for percentages 70 to 84, D for percentages 60 to 69 and F for all other percentages:

Percentage=”Per”

Print “Failed” Print “Passed” [Per>=50]

[Per<50]

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

20

If percentage is greater than or equal to 90 Print “A” else If percentage is greater than or equal to 85 Print “B” else If percentage is greater than or equal to 70 Print “C” else If percentage is greater than or equal to 60 Print “D” else Print “F” Code Format:

if ( Percentage >= 90 ) { System.out.println( "A" ); } else if ( Percentage >= 85 ) { System.out.println( "B" ); } else if ( Percentage >= 70 ) { System.out.println( "C" ); } else if ( Percentage >= 60 ) { System.out.println( "D" ); } else { System.out.println( "F" );

}

If variable percentage is greater than or equal to 90, the first four conditions in the nested if…else statement will be true, but only the statement in the if part of the first

if…else statement will execute. After that statement executes, the else part of the “outermost” if…else statement is skipped. Many programmers prefer to write the preceding

nested if…else statement as

if ( Percentage >= 90 ) System.out.println( "A" ); else if ( Percentage >= 85 ) System.out.println( "B" ); else if ( Percentage >= 70 )

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

21

System.out.println( "C" ); else if ( Percentage >= 60 ) System.out.println( "D" ); else System.out.println( "F" ); The two forms are identical except for the spacing and indentation, which the compiler ignores. The latter form avoids deep indentation of the code to the right. Such indentation often leaves little room on a line of source code, forcing lines to be split. Dangling-else Problem The Java compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({ and }). This behavior can lead to what is referred to as the dangling-else problem. For example, see the solution. if ( x > 15 ) if ( y > 15 ) System.out.println( "x and y are > 15" ); else System.out.println( "x is <= 15" ); It appears to indicate that if x is greater than 5, the nested if statement determines whether y is also greater than 5. If so, the string "x and y are > 5" is output. Otherwise, it appears that if x is not greater than 5, the else part of the if…else outputs the string "x is <= 5". Beware! This nested if…else statement does not execute as it appears. The compiler actually interprets the statement as if ( x > 5 ) if ( y > 5 ) System.out.println( "x and y are > 5" ); else System.out.println( "x is <= 5" ); in which the body of the first if is a nested if…else. The outer if statement tests whether x is greater than 5. If so, execution continues by testing whether y is also greater than 5. If the second condition is true, the proper string—"x and y are > 5"—is displayed. However, if the second condition is false, the string "x is <= 5" is displayed, even though we know that x is greater than 5. Equally bad, if the outer if statement’s condition is false, the inner if…else is skipped and nothing is displayed. To force the nested if…else statement to execute as it was originally intended, you have to write it as follows: if ( x > 5 ) { if ( y > 5 ) System.out.println( "x and y are > 5" ); } else System.out.println( "x is <= 5" );

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

22

The braces indicate that the second if is in the body of the first and that the else is associated with the first if. Blocks The if statement normally expects only one statement in its body. To include several statements in the body of an if (or the body of an else for an if…else statement), enclose the statements in braces. Statements contained in a pair of braces form a block. A block can be placed anywhere in a program that a single statement can be placed. The following example includes a block in the else part of an if…else statement: if ( Percentage >= 50 ) System.out.println( "Passed" ); else { System.out.println( "Failed" ); System.out.println( "You must take this course again." ); } In this case, if percentage is less than 50, the program executes both statements in the body of the else and prints Failed You must take this course again. Note the braces surrounding the two statements in the else clause. These braces are important. Without the braces, the statement System.out.println( "You must take this course again." ); would be outside the body of the else part of the if…else statement and would execute regardless of whether the grade was less than 50. Syntax errors (e.g., when one brace in a block is left out of the program) are caught by the compiler. A logic error (e.g., when both braces in a block are left out of the program) has its effect at execution time. A fatal logic error causes a program to fail and terminate prematurely. A nonfatal logic error allows a program to continue executing but causes it to produce incorrect results. Just as a block can be placed anywhere a single statement can be placed, it’s also possible to have an empty statement. The empty statement is represented by placing a semicolon (;) where a statement would normally be. System.out.println(); Switch Statement (Multiple Selection Statements): The switch statement can be used to choose one among many alternative actions, based on the value of an expression. Its general form is as follows:

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

23

switch (<switch expression>) { case label1: <statement1> case label2: <statement2> ... case labeln: <statementn> default: <statement> } // end switch

The switch expression is evaluated first. If the value is a wrapper type, an unboxing conversion is performed.

The value of the switch expression is compared with the case labels. Control is transferred to the <statementi> associated with the case label that is equal to the value of the switch expression. After execution of the associated statement, control falls through to the next statement unless appropriate action is taken.

If no case label is equal to the value of the switch expression, the statement associated with the default label is executed.

e. Introduction to loops

Loop causes a section of a program, it continues when the condition is true, it stops when the condition becomes false and control passes over to the statements following the loop. Or A repetition (or looping) statement allows you to specify that a program should repeat an action while some condition remains true.

While there are more items on my shopping list Purchase next item and cross it off my list

Consider a program segment that finds the first power of 3 larger than 100. Suppose that the int variable item is initialized to 3. After the following while statement executes, item contains the result: The syntax of the while loop is while (<loop condition>) <loop body> While (item <= 100 ) item = 3 * item; When this while statement begins execution, the value of variable item is 3. Each iteration of the while statement multiplies item by 3, so item takes on the values 9, 27, 81 and 243 successively. When variable item becomes 243, the while-statement condition—item <= 100—becomes false. This terminates the repetition, so the final value of item is 243. At this point, program execution continues with the next statement after the while statement.

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

24

Consider the Algorithm: Set total to zero Set grade counter to one While grade counter is less than or equal to ten Prompt the user to enter the next grade Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average The do-while Statement The syntax of the do-while loop is do <loop body> while (<loop condition>); The <loop condition> is evaluated after executing the <loop body>. The value of the <loop condition> is subjected to unboxing if it is of the type Boolean. The do-while statement executes the <loop body> until the <loop condition> becomes false. When the <loop condition> becomes false, the loop is terminated and execution continues with the statement immediately following the loop. Note that the <loop body> is executed at least once. do { mice.play(); } while (cat.isAway()); For Loop (Statement)

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

25

Format of a for Statement The general format of the for statement is

for ( initialization; loopContinuationCondition; increment ) statement

where the initialization expression names the loop’s control variable and optionally provides its initial value, loopContinuationCondition determines whether the loop should continue executing and increment modifies the control variable’s value (possibly an increment or decrement), so that the loop-continuation condition eventually becomes false. The two semicolons in the for header are required. If the loop-continuation condition is initially false, the program does not execute the for statement’s body. Instead, execution proceeds with the statement following the for. Arithmetic Expressions in For Loop: for ( int j = x; j <= 4 * x * y; j += y / x ) for ( int j = 2; j <= 80; j += 5 ) Arithmetic Increment/Decrement Examples a) Vary the control variable from 1 to 100 in increments of 1. for ( int i = 1; i <= 100; i++ ) b) Vary the control variable from 100 to 1 in decrements of 1. for ( int i = 100; i >= 1; i-- ) c) Vary the control variable from 7 to 77 in increments of 7. for ( int i = 7; i <= 77; i += 7 ) d) Vary the control variable from 20 to 2 in decrements of 2. for ( int i = 20; i >= 2; i -= 2 ) e) Vary the control variable over the values 2, 5, 8, 11, 14, 17, 20. for ( int i = 2; i <= 20; i += 3 ) f) Vary the control variable over the values 99, 88, 77, 66, 55, 44, 33, 22, 11, 0. for ( int i = 99; i >= 0; i -= 11 )

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

26

The for(;;) Statement The for(;;) loop is the most general of all the loops. It is mostly used for countercontrolled loops, i.e., when the number of iterations is known beforehand. The syntax of the loop is as follows: for (<initialization>; <loop condition>; <increment expression>) <loop body> The <initialization> usually declares and initializes a loop variable that controls the execution of the <loop body>. The <loop condition> must evaluate to a boolean or a Boolean value. The for(:) Statement The enhanced for loop is convenient when we need to iterate over an array or a collection, especially when some operation needs to be performed on each element of the array or collection. Some examples of for(:) loops that are legal: (Array will be discussed in Arrays) // Some 1-dim arrays: int[] intArray = {10, 20, 30}; Integer[] intObjArray = {10, 20, 30}; String[] strArray = {"one", "two"}; // Some 2-dim arrays: Object[][] objArrayOfArrays = {intObjArray, strArray}; Number[][] numArrayOfArrays = {{1.5, 2.5}, intObjArray, {100L, 200L}}; int[][] intArrayOfArrays = {{20}, intArray, {40}}; // Iterate over an array of Strings. // Expression type is String[], and element type is String. // String is assignable to Object. for (Object obj : strArray) {} // Iterate over an array of ints. // Expression type is int[], and element type is int. // int is assignable to Integer (boxing conversion) for (Integer iRef : intArrayOfArrays[0]){} // Iterate over an array of Integers. // Expression type is Integer[], and element type is Integer. // Integer is assignable to int (unboxing conversion) for (int i : intObjArray){} // Iterate over a 2-dim array of ints. // Outer loop: expression type is int[][], and element type is int[]. // Inner loop: expression type is int[], element type is int.

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

27

for (int[] row : intArrayOfArrays) for (int val : row) {} // Iterate over a 2-dim array of Numbers. // Outer loop: expression type is Number[][], and element type is Number[]. // Outer loop: Number[] is assignable to Object[]. // Inner loop: expression type is Object[], element type is Object. for (Object[] row : numArrayOfArrays) for (Object obj : row) {} // Outer loop: expression type is Integer[][], and element type is Integer[]. // Outer loop: Integer[] is assignable to Number[]. // Inner loop: expression type is int[], and element type is int. // Inner loop: int is assignable to double. for (Number[] row : new Integer[][] {intObjArray, intObjArray, intObjArray}) for (double num : new int[] {}) {}

f. Jump Statements Break: The break statement comes in two forms: the unlabeled and the labeled form. break; // the unlabeled form break <label>; // the labeled form The unlabeled break statement terminates loops (for(;;), for(:), while, do-while) and switch statements, and transfers control out of the current context (i.e., the closest enclosing block). The rest of the statement body is skipped, and execution continues after the enclosing statement. class Breakes { public static void main(String[] args) { for (int i = 1; i <= 5; ++i) { if (i == 4) break; // (1) Terminate loop. Control to (2). // Rest of loop body skipped when i gets the value 4. System.out.printf("%d %.2f%n", i, Math.sqrt(i)); } // end for // (2) Continue here. int n = 2; switch (n) { case 1:

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

28

System.out.println(n); break; case 2: System.out.println("Inner for loop: "); for (int j = 0; j <= n; j++) if (j == 2) break; // (3) Terminate loop. Control to (4). else System.out.println(j); default: System.out.println("default: " + n); // (4) Continue here. } } } Output from the program: 1 1.00 2 1.41 3 1.73 Inner for loop: 0 1 default: 2 A labeled break statement can be used to terminate any labeled statement that contains the break statement. Control is then transferred to the statement following the enclosing labeled statement. In the case of a labeled block, the rest of the block is skipped and execution continues with the statement following the block: out: { // (1) Labeled block if (j == 10) break out; // (2) Terminate block. Control to (3). System.out.println(j); // Rest of the block not executed if j == 10. } The continue Statement Like the break statement, the continue statement also comes in two forms: the unlabeled and the labeled form. continue; // the unlabeled form continue <label>; // the labeled form The continue statement can only be used in a for(;;), for(:), while, or do-while loop to prematurely stop the current iteration of the loop body and proceed with the next iteration, if possible. In the case of the while and do-while loops, the rest of the

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

29

loop body is skipped, that is, stopping the current iteration, with execution continuing with the <loop condition>. In the case of the for(;;) loop, the rest of the loop body is skipped, with execution continuing with the <increment expression>. class Jump { public static void main(String[] args) { for (int i = 1; i <= 5; ++i) { if (i == 4) continue; // (1) Control to (2). // Rest of loop body skipped when i has the value 4. System.out.printf("%d %.2f%n", i, Math.sqrt(i)); // (2) Continue with increment expression. } // end for } } Output from the program: 1 1.00 2 1.41 3 1.73 5 2.24

4. Introducing Classes

a. Creating Classes and Objects Class GradeProgress The GradeProgress class declaration contains a displayMessage method (lines 7– 10) that displays a message on the screen. Yor’ll need to make an object of this class and call its method to execute line 9 and display the message. The class declaration begins in line 4. The keyword public is an access modifier. For now, you’ll simply declare every class public. Every class declaration contains keyword Class declaration with one method 1 GradeProgress.java 2 Class declaration with one method. 3 4 public class GradeProgress 5 { 6 display a welcome message to the GradeProgress user 7 public void displayMessage() //Method defined 8 { 9 System.out.println( "Welcome to the Grade Progress!" ); 10 } // end method displayMessage 11 } // end class GradeProgress Creating and Calling Instance Method: . 1// GradeProgressTest.java

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

30

2 // Creating a GradeProgress object and calling its displayMessage method. 3 4public class GradeProgressTest 5 { 6 // main method begins program execution 7 public static void main( String[] args ) 8 { 9 // create a GradeProgress object and assign it to myGradeProgress 10 GradeProgress myGradeProgress = new GradeProgress(); 11 12 // call myGradeProgress's displayMessage method 13 myGradeProgress.displayMessage(); 14 } // end main 15 } // end class GradeProgressTest

b. Instance Variables 1 GradeProgress.java 2 // GradeProgress class that contains a courseName instance variable 3 // and methods to set and get its value. 45 public class GradeProgress 6 { 7 private String courseName; // course name for this GradeProgress (instance variable) 8 9// method to set the course name 10public void setCourseName( String name ) 11{ 12courseName = name; // store the course name 13} // end method setCourseName 14 15// method to retrieve the course name 16public String getCourseName() 17{ 18return courseName; 19} // end method getCourseName 20 21// display a welcome message to the GradeProgress user 22 public void displayMessage 23 { 24 // calls getCourseName to get the name of 25 // the course this GradeProgress represents 26 System.out.printf( "Welcome to the grade book for\n%s!\n", 27 getCourseName() ); 28 } // end method displayMessage 29 } // end class GradeProgress A typical instructor teaches more than one course, each with its own course name. Line 7 declares courseName as a variable of type String. Because the variable is declared

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

31

in the body of the class but outside the bodies of the class’s methods (lines 10–13, 16–19 and 22–28), line 7 is a declaration for an instance variable. Every instance (i.e., object) of class GradeProgress contains one copy of each instance variable. For example, if there are two GradeProgress objects, each object has its own copy of courseName. A benefit of making courseName an instance variable is that all the methods of the class (in this case, GradeProgress) can manipulate any instance variables that appear in the class (in this case, course-Name).

c. Methods Methods setCourseName and getCourseName Method setCourseName (lines 10–13) does not return any data when it completes its task, so its return type is void. The method receives one parameter—name—which represents the course name that will be passed to the method as an argument. Line 12 assigns name to instance variable courseName. Method getCourseName (lines 16–19) returns a particular GradeProgress object’s courseName. The method has an empty parameter list, so it does not require additional information to perform its task. The method specifies that it returns a String—this is the method’s return type. When a method that specifies a return type other than void is called and completes its task, the method returns a result to its calling method. Similarly, when a statement calls method getCourseName on a GradeProgress object, the statement expects to receive the GradeProgress’s course name (in this case, a String, as specified in themethod declaration’s return type). The return statement in line 18 passes the value of instance variable courseName back to the statement that calls method getCourseName. Consider, method displayMessage’s line 27, which calls method getCourseName. When the value is returned, the statement in lines 26–27 uses that value to output the course name. The statements in lines 12 and 18 each use courseName even though it was not declared in any of the methods. We can use courseName in GradeProgress’s methods because course- Name is an instance variable of the class. Method displayMessage Method displayMessage (lines 22–28) does not return any data when it completes its task, so its return type is void. The method does not receive parameters, so the parameter list is empty. Lines 26–27 output a welcome message that includes the value of instance variable courseName, which is returned by the call to method getCourseName in line 27. Notice that one method of a class (displayMessage in this case) can call another method of the same class by using just the method name (getCourseName in this case).

d. Initializer An initializer is a line of code (or a block of code) placed outside any method, constructor, or other block of code. Initializers are executed whenever an instance of a class is created, regardless of which constructor is used to create the instance. The simplest initializers are those that declare and initialize fields. For example:

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

32

class Class1 { public int x = 0; // other class constructors and members go here } The variable x is declared and initialized to a value of 0 (zero). An initializer can also be a block of code enclosed within parentheses, as in this example: class PClass { private Scanner sc = new Scanner(System.in); public int x; { System.out.print( "Enter the starting value for x: "); x = sc.nextInt(); } }

1. What are instance variable initializer, instance initializer and static initializer?

public class Inits { //instance variable initializer String s = "abc"; //constructor public Inits() { System.out.println("Constructor called"); } //static initializer static { System.out.println("Static Initializer called"); } //instance initializer { System.out.println("Instance Initializer called"); }

Some other useful information concerning

initializers:

If a class contains more than one initializer, the initializers are executed in the order in which they appear in the program.

Initializers are executed before any class constructors.

Although including all initializers at the beginning of the class is common — before any constructors or methods — this ordering isn’t a requirement. Initializers can appear anywhere within a class.

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

33

public static void main(String[] args) { new Inits(); new Inits(); }

} Output: static initializer called instance initializer called constructor called instance initializer called constructor called

2. How does Java instance initializer work? The instance initializer above contains a print statement. To understand how it works, we

can think of it as a variable assignment statement(e.g. b = 0), then this would not difficult to

understand.

Instead of

int b = 0, you could write int b; b = 0; Therefore, instance initializer and instance variable initializer are pretty much the same.

3. When are instance initializers useful? The use of instance initializers are rare, but still it can be a useful alternative to instance

variable initializers if:

(1) initializer code must handle exceptions

(2) perform calculations that can’t be expressed with an instance variable initializer.

Of course, such code could be written in constructors. But if a class had multiple

constructors, you would have to repeat the code in each constructor.

With an instance initializer, you can just write the code once, and it will be executed no

matter what constructor is used to create the object. (I guess this is just a concept, and it is

not used often.)

Another case in which instance initializers are useful is anonymous inner classes, which

can’t declare any constructors at all. (Will this be a good place to place a logging function?)

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

34

The static initializer block is a very interesting item in Java that unknown by most of the

Java novice community. Understanding “what it is” and “how it works” are two very

important concepts about static initializers that every Java developer should know.

What Is It?

A block of code ‘{ }’ that runs only one time, and it is run the first time the Constructor or the

main() method for that class is called (Sun calls this ‘when the class is initialized‘)

How Does It Work?

Just declare a static { } block inside your Java class and throw some code in it No return statement No access to this or super Can throw Unchecked Exceptions only What Can It Be Used For? Loading drivers and other items into the namespace. (For example ‘Class.forName(“com.mysql.jdbc.Driver”)’) Initialize your complex static members once (possibly for singletons/etc) Logging Creating/parsing prepared SQL statements Time to Play

2 simple classes to play around with the static initializer class: Loader and Test: class Loader {

static final String theName = "The Loader";

static {

System.out.println("Loader.static");

}

Loader() {

System.out.println("Loader.Loader()");

}

}

class Test {

static {

System.out.println( "Test.static");

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

35

}

Test() {

System.out.println( "Test.Test()");

}

public static void main( String [] args ) {

System.out.println( "Test.main");

Test t = new Test();

System.exit(0);

}

}

If we compile and run Test the output we see is:

Test.static Test.main Test.Test() So we see that static block code is called before the main method is executed. Now, let’s define a Loader variable in the constructor and print out ‘Loader.name’. class Test {

static {

System.out.println( "Test.static");

}

Test() {

System.out.println( "Test.Test()");

// Define a loader and print out the static name

Loader l;

System.out.println( Loader.theName );

}

public static void main( String [] args ) {

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

36

System.out.println( "Test.main");

Test t = new Test();

System.exit(0);

}

}

When we compile Test and run it, we now see this:

Test.static Test.main Test.Test() The Loader

So, we can see that neither defining a class nor accessing static class members constitutes

“initializing” a class (which would call the static block).

Lets initialize a few instances of a Loader instead: class Test {

static {

System.out.println( "Test.static");

}

Test() {

System.out.println( "Test.Test()");

// Make a few Loaders

Loader l1 = new Loader(); Loader l2 = new Loader(); Loader l3 = new Loader(); }

public static void main( String [] args ) {

System.out.println( "Test.main");

Test t = new Test();

System.exit(0);

} }

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

37

Now we compile and execute and we get the expected output:

Test.static Test.main Test.Test() Loader.static Loader.Loader() Loader.Loader() Loader.Loader()

The static block was called only once before the first time the constructor was called.

What About Inheritance? (Note: Inheritance, which is the coming topic, you are doing this to understand the concept

of Initializer’s Inheritance).

A Test is being inherited from Loader.

class Test extends Loader {

static {

System.out.println( "Test.static");

}

Test() {

System.out.println( "Test.Test()");

}

public static void main( String [] args ) {

System.out.println( "Test.main");

Test t = new Test();

System.exit(0);

}

}

Now if you compile and run Test you get the output:

Loader.static Test.static Test.main

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

38

Loader.Loader() Test.Test()

The static blocks get loaded first as usual, but the Loader class had it’s static block called

first, which makes sense.

5. Arrays

a. Arrays

Arrays in Java –Basic Array

An array is a flexible structure for storing a sequence of values all of the same type. Array A structure that holds multiple values of the same type. The values stored in an array are called elements. The individual elements are accessed using an integer index. Index An integer indicating the position of a value in a data structure. As an analogy, consider post office boxes. The boxes are indexed with numbers, so you can refer to an individual box by using a description like “PO Box 884.” You already have experience using an index to indicate positions within a String, when calling methods like charAt or substring As was the case with String indexes, array indexes start with 0. This is a convention known as zero-based indexing. Zero-Based Indexing A numbering scheme used throughout Java in which a sequence of values is indexed starting with 0 (element 0, element 1, element 2, and so on). Auto-Initialization The initialization of variables to a default value, as in the initialization of array elements when an array is constructed.

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

39

Zero Equivalent Values – While Auto Initialize

Type Value

Integer (int) 0

Double (double) 0.0

Char (char) ‘\0’

Boolean (boolean) False (false)

Objects (objects) Null (null)

When Java performs auto-initialization, it always initializes to the zero-equivalent for the type. In the table above, indicates the zero-equivalent values for various types. Notice that the zero-equivalent for type double is 0.0 , which is why the array elements were initialized to that value. Using the indexes, you can store the specific temperature values you want to work with: temperature[0] = 74.3; temperature[1] = 68.4; temperature[2] = 70.3; This code modifies the array to have the following values: Obviously an array isn’t particularly helpful when you have just three values to store, but you can request a much larger array. For example, you could request an array of 100 temperatures by saying: double[] temperature = new double[100]; This is almost the same line of code you executed before. The variable is still declared to be of type double[], but in constructing the array you request 100 elements instead of 3, which constructs a much larger array: Notice that the highest index is 99 rather than 100 because of zero-based indexing. You are not restricted to simple literal values inside the brackets. You can use any integer expression. This allows you to combine arrays with loops, which greatly simplifies the code you write. For example, suppose you want to read a series of temper- natures from a Scanner . You could read each value individually, as in: temperature[0] = input.nextDouble(); temperature[1] = input.nextDouble(); temperature[2] = input.nextDouble(); ... temperature[99] = input.nextDouble();

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

40

But since the only thing that changes from one statement to the next is the index, you can capture this pattern in a for loop with a control variable that takes on the values 0 to 99 : for (int i = 0; i < 100; i++) { temperature[i] = input.nextDouble(); } This is a very concise way to initialize all the elements of the array. The preceding code works when the array has a length of 100, but you can imagine the array having a different length. Java provides a useful mechanism for making this code more gen- eral. Each array keeps track of its own length. You’re using the variable temperature to refer to your array, which means you can ask for temperature.length to find out the length of the array. By using temperature.length in the for loop test instead of the specific value 100, you make your code more general: for (int i = 0; i < temperature.length; i++) { temperature[i] = input.nextDouble(); } Notice that the array convention is different from the String convention. If you have a String Variable ‘s’, you ask for the length of the String by referring to s.length() For an array variable, you don’t include the parentheses after the word “length.” This is another one of those unfortunate inconsistencies that Java programmers just have to memorize. The previous code provides a pattern that you will see often with array-processing code: A for loop that starts at 0 and that continues while the loop variable is less than the length of the array, doing something with element [i] in the body of the loop. Declaring Arrays: int[] marks; byte[] age; Less readable: int marks[]; byte age[];

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

41

Construction int[] marks; marks = new int[5]; “The size of the array is mandatory” In single line: int[] marks = new int[5]; marks Initialization Initialization is loading the array with the values.

Note: Always remember that the Array range must be lesser than the subscript. (5) is the subscript. int[] marks = new int[5]; marks[0] =11; marks[1] =29; marks[2] =14; marks[3] = 47; marks[4] = 54; Array Initializer int[] marks ={20,39,40,30}; Array Initializer (curly brackets { }) Two dimensional Array int[][] marks = new int[2][3]; marks[0][0]=30; marks[0][1]=31; marks[0][2]=32; marks[1][0]=40; marks[1][1]=41; marks[1][2]=42;

Location

0

1

2

3

4

Subscript

Lower Bound

Upper Bound

Correct Range

Wrong Range

Element 11 29 14 47 54 (0-4)=5 0 4 < 5 <=5/>=5

0 1

30 31 32

40 41 42

Java Crash Course – Java 1 LECTURE CONTENTS

Total Course Length: 37 Classes or 40 Duration: 45 Minutes For Each Content

Theory Classes: 28 Practical Classes: 9(+3) = 12

By Sabihuddin Ahmed Siddiqui Email: [email protected]

Contact: 00923002730073

42

Bibliography: Thanks to all the people all over the world, whom I discussed in producing this course and websites, resources and material reference used in this document.

Sabihuddin Ahmed Siddiqui.