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

Lesson 2 - Java Programming Fundamentals

This document provides an overview of Java programming fundamentals, including the concepts of objects, classes, methods, and variables. It explains key terms such as instantiation, access modifiers, and the compilation process, as well as the structure of a simple Java program. Additionally, it covers variable types, basic data types, and commenting in Java, along with examples to illustrate these concepts.

Uploaded by

isaacloben089
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lesson 2 - Java Programming Fundamentals

This document provides an overview of Java programming fundamentals, including the concepts of objects, classes, methods, and variables. It explains key terms such as instantiation, access modifiers, and the compilation process, as well as the structure of a simple Java program. Additionally, it covers variable types, basic data types, and commenting in Java, along with examples to illustrate these concepts.

Uploaded by

isaacloben089
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Lesson 2:

Fundamentals of Java Programming


A simple Java Program
 We consider a Java program as a collection of objects that communicate via invoking each
other's methods.

1. Object − Objects have states and behaviors.

Example: A dog has states - color, name, breed as well as behavior such as wagging their tail,
barking, eating. An object is an instance of a class.

2. Class − A class can be defined as a template/blueprint that describes the behavior/state that
the object of its type supports.

3. 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.

4. Instance Variables − Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.

A class can define both attributes and behaviours. Again attributes are defined by variables and behaviours are
represented by methods. In other words, methods define the abilities of an object.
Definition of terms

1. Instantiate To create an object based on the description supplied by a class.

2. Package A collection of related classes or A named collection of object classes in Java that can be
imported by a program. Packages are imported into a source file to save typing the full name of the
class (e.g., can say “Person” instead of “org.eclipsetraining.librarytutorial.Person” and to avoid the
possibility of two classes having identical names.

3. Instantiation Creating an object, which is an instance of a class

4. Access Modifier: Reserved words “public”, “private”, “protected” in Java. Control whether
classes and members may be accessed from any class, only this class, subclasses. Default is access
from any class in the package.

5. (API) Application Programming Interface: The way one program uses another program. In Java,
the API can be thought of as the collection of public methods for a class or package.

6. IDE (Integrated Development Environment): Program, like Eclipse, that provides the different tools
required to develop a software package.
Template of a java program
Lets Get Started
// Text-printing program.

public class Welcome1


{
// main method begins execution of Java application
public static void main( String[] args )
{
System.out.println( "Welcome to Java Programming!" );
} // end method main
} // end class Welcome1
Understanding first java program
1. class keyword is used to declare a class in java.

2. public keyword is an access modifier which represents visibility, it means it is visible to all.

3. static is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static method.
The main method is executed by the JVM, so it doesn't require to create object to invoke the main
method. So it saves memory.

4. void is the return type of the method, it means it doesn't return any value.

5. main represents startup of the program.

6. String[] args is used for command line argument.

7. System.out object is known as the standard output object. It allows a Java applications to display
information in the command window from which it executes.

8. println() is a method that is used print statement.


1. System: system class provides facilities such as standard input, output and error
streams.

2. out: out is an object of PrintStream class defined in System class

3. println(“ “); println() is a method of PrintStream class


Compilation Process

After compiling when you will try to run the byte code(.class file), the
following steps are performed at runtime:-

 Class loader loads the java class. It is subsystem of JVM Java


Virtual machine.

 Byte Code verifier checks the code fragments for illegal codes that
can violate access right to the object.

 Interpreter reads the byte code stream and then executes the
instructions, step by step.
Modifiers and Reserved Words

Modifiers

 Java uses certain reserved words called modifiers that specify the properties of the data, methods, and
classes and how they can be used. Examples of modifiers are public, static, private, final, abstract, and
protected. A public datum, method, or class can be accessed by other programs. A private datum or
method cannot be accessed by other programs.

Reserved Words
 Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used
for other purposes in the program. For example, when the compiler sees the word class, it understands
that the word after class is the name for the class. Other reserved words in are public, static, and void.
Modifiers and Reserved Words
Commenting Your Programs

 The java comments are statements that are not executed by the compiler and interpreter.

 The comments can be used to provide information or explanation about the variable, method,
class or any statement.

 It can also be used to hide program code for specific time.

 There are 3 types of comments in java.

1. Single Line Comment

2. Multi Line Comment

3. Documentation Comment
Single Line Comment
 The single line comment is used to comment only one line.

Syntax:
//This is single line comment

Example:
public class Welcome1 {
// main method begins execution of Java application
public static void main( String[] args ) {
System.out.println( "Welcome to Java Programming!" );
}
}
Multi Line Comment

 The multi line comment is used to comment multiple lines of code. Syntax is as follows:
/*
This is multi line
comment
*/

Example:
public class Welcome1
{
/* main method begins
execution of Java application */
public static void main( String[] args )
{
System.out.println( "Welcome to Java Programming!" );
}
}
Documentation Comment

 The documentation comment is used to create documentation API.


 To create documentation API, you need to use javadoc tool. Syntax:
/**
This is documentation
comment
*/

Example:
public class Welcome1 {
/** main method begins
execution of Java application
*/
public static void main( String[] args ) {
System.out.println( "Welcome to Java Programming!" );
}
}
Basic Points to keep in mind
1. Case Sensitivity − Java is case sensitive, which means identifier Hello and hello
would have different meaning in Java.

2. Class Names − For all class names the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first
letter should be in Upper Case.

Example: class MyFirstJavaClass

3. Method Names − All method names should start with a Lower Case letter. If
several words are used to form the name of the method, then each inner
word's first letter should be in Upper Case.

Example: public void myMethodName()


4. Program File Name − Name of the program file should exactly match the
class name. When saving the file, you should save it using the class name
(Remember Java is case sensitive) and append '.java' to the end of the
name (if the file name and the class name do not match, your program
will not compile).

Example: Assume 'MyFirstJavaProgram' is the class name. Then


the file should be saved as 'MyFirstJavaProgram.java‘

5. public static void main(String args[]) − Java program processing starts


from the main() method which is a mandatory part of every Java
program.
6. Blocks {……} – A pair of braces in a program forms a block that groups
components of a program

7. main method – provides the control of program flow. The java interpreter
executes the application by invoking the main method. It is the first routine that
is run when the program is executed.

Example: public static void main(String[] args) {


// statements

}
Displaying a Single Line of Text with Multiple Statement

public class Welcome2


{
public static void main( String[] args )
{
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );
}
}
 The first statement uses System.out’s method print to display a string.
 Each print or printf statement resumes displaying characters from where the last
print or printf statement stopped displaying characters.
 Unlike println, after displaying its argument, print does not position the output
cursor at the beginning of the next line in the command window—the next
character the program displays will appear immediately after the last character that
print displays.
Displaying Multiple Lines of Text with a Single Statement

public class Welcome3


{
public static void main( String[] args )
{
System.out.println( "Welcome \nto \nJava\n Programming!" );
}
}

 Normally, the characters in a string are displayed exactly as they appear in the double quotes.
However, that the paired characters \ and n do not appear on the screen. The backslash (\) is an
escape character which has special meaning to System.out’s print and println methods.
 When a backslash appears in a string, Java combines it with the next character to form an escape
sequence. The escape sequence \n represents the newline character.
 When a newline character appears in a string being output with System.out, the newline character
causes the screen’s output cursor to move to the beginning of the next line in the command
window.
Special escape sequences for String and char literals

Notation Character represented


\n Newline (0x0a)
\r Carriage return (0x0d)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\" Double quote
\' Single quote
\\ backslash
Displaying Text with printf
public class Welcome4
{
public static void main( String[] args )
{
System.out.printf( "%s\n%s\n","Welcome to", "Java Programming!" );
}
}

 Method printf’s first argument is a format string that may consist of fixed text and format
specifiers.
 Fixed text is output by printf just as it would be by print or println. Each format specifier is a
placeholder for a value and specifies the type of data to output.
 Format specifiers also may include optional formatting information.
 Format specifiers begin with a percent sign (%) followed by a character that represents the data
type. For example, the format specifier %s is a placeholder for a string.
Java Identifiers
 All Java components require names. Names used for classes, variables, and methods are
called identifiers.

 Rules for Java identifiers are as follows −

1) All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).

2) After the first character, identifiers can have any combination of characters.

3) A key word cannot be used as an identifier.

4) Most importantly, identifiers are case sensitive.

Examples of legal identifiers: age, $salary, _value, __1_value

Examples of illegal identifiers: 123abc, -salary


Variable types

1. Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and
the variable will be destroyed when the method has completed.

2. Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.

3. Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
Variable Declaration
 In Java you must declare all variables before they can be used.
 The basic form of a variable declaration is as follows−
data type variable [ = value][, variable [ = value] ...] ;

Example
• int a, b, c; // Declares three int types, a, b, and c.
• int a = 10, b = 10; // Example of initialization
• byte B = 22; // initializes a byte type variable B.
• double pi = 3.14159; // declares and assigns a value of PI.
• char a = 'a'; // the char variable a is initialized with value 'a'
Basic Datatypes

 Variables are reserved memory locations to store values. This means that when you
create a variable you reserve some space in the memory.

 Based on the data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types
to variables, you can store integers, decimals, or characters in these variables.

 There are two data types available in Java −

1. Primitive Data Types

2. Reference/Object Data Types


Primitive Data Types

 Primitive datatypes are predefined by the language and named by a keyword.


 There are eight primitive datatypes supported by Java.
1. byte

 Byte data type is an 8-bit signed two's complement integer


 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an integer.

Example: byte a = 100, byte b = -50


2. short

 Short data type is a 16-bit signed two's complement integer


 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2
times smaller than an integer
 Default value is 0.

Example: short s = 10000, short r = -20000


3. int

 Int data type is a 32-bit signed two's complement integer.


 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values unless there is
a concern about memory.
 The default value is 0

Example: int a = 100000, int b = -200000


4. long
 Long data type is a 64-bit signed two's complement integer
 Minimum value is -9,223,372,036,854,775,808(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
 This type is used when a wider range than int is needed
 Default value is 0L

Example: long a = 100000L, long b = -200000L


5. float
 Float data type is a single-precision 32-bit IEEE 754 floating point
 Float is mainly used to save memory in large arrays of floating point numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency

Example: float f1 = 234.5f


6. double

 double data type is a double-precision 64-bit IEEE 754 floating point


 This data type is generally used as the default data type for decimal values,
generally the default choice
 Double data type should never be used for precise values such as currency
 Default value is 0.0d

Example: double d1 = 123.4


7. boolean
 Boolean data type represents one bit of information
 There are only two possible values: true and false
 This data type is used for simple flags that track true/false conditions
 Default value is false

Example: boolean one = true


8. char

 char data type is a single 16-bit Unicode character


 Minimum value is '\u0000' (or 0)
 Maximum value is '\uffff' (or 65,535 inclusive)
 Char data type is used to store any character

Example: char letterA = 'A'


Reference Datatypes
 Reference variables are created using defined constructors of the classes. They
are used to access objects. These variables are declared to be of a specific type
that cannot be changed. For example, Employee, Puppy, etc.
 Class objects and various type of array variables come under reference
datatype.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the declared type or any
compatible type.

Example: Animal animal = new Animal("giraffe");


Java Literals

 A literal is a source code representation of a fixed value. They are represented directly
in the code without any computation. Literals can be assigned to any primitive type
variable. For example −
int a = 68;
char a = 'A'

 String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes. For examples −
String a = "Hello World"
Java operators

 An operator takes one or more arguments and produces a new value.


 Addition (+), subtraction and unary minus (-), multiplication (*), division (/), and
assignment (=) all work much the same in any programming language.
 All operators produce a value from their operands. In addition, an operator can
change the value of an operand. This is called a side effect.
Using Java operators
 Java provides a rich set of operators to manipulate variables.
 We can divide all the Java operators into the following groups −

1. Arithmetic Operators

2. Relational Operators

3. Bitwise Operators

4. Logical Operators

5. Assignment Operators

6. Misc Operators
Arithmetic Operators

 Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra. Assume integer variable A holds 10 and variable B holds 20, then

Relational Operators
 A condition is an expression that can be true or false. The following are
relational operators supported by Java language. Assume variable A holds 10 and
variable B holds 20, then −
The Logical Operators

 The following table lists the logical operators. Assume Boolean variables A
holds true and variable B holds false, then −
Assignment Operators

 Following are the assignment operators supported by Java language −


Bitwise Operators
 Java defines several bitwise operators, which can be applied to the integer
types, long, int, short, char, and byte.
 Bitwise operator works on bits and performs bit-by-bit operation. Assume if a =
60 and b = 13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Bitwise Operators (Cont’d)

 Assume integer variable A holds 60 and variable B holds 13 then −


Miscellaneous - Conditional Operator (? :)

 Conditional operator is also known as the ternary operator.


 This operator consists of three operands and is used to evaluate Boolean
expressions.
 The goal of the operator is to decide, which value should be assigned to the
variable.
 The operator is written as −

variable x = (expression) ? value if true : value if false


Conditional Operator ( ? : ) - Example

public class Test {

public static void main(String args[]) {


int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " +
b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}
Miscellaneous Operators - instanceof
 This operator is used only for object reference variables.
 The operator checks whether the object is of a particular type (class type or
interface type).
 instanceof operator is written as −

•( Object reference variable ) instanceof (class/interface type)


 If the object referred by the variable on the left side of the operator passes the
IS-A check for the class/interface type on the right side, then the result will be
true.
instanceof Operator – Example 1

public class Test {

public static void main(String args[]) {

String name = "James";

// following will return true since name is type of String


boolean result = name instanceof String;
System.out.println( result );
}
}
instanceof Operator – Example 2

class Vehicle {}

public class Car extends Vehicle {

public static void main(String args[]) {

Vehicle a = new Car();


boolean result = a instanceof Car;
System.out.println( result );
}
}
Precedence of Java Operators

 Operator precedence determines the grouping of terms in an expression.


 This affects how an expression is evaluated.
 Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −
 For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has
higher precedence than +, so it first gets multiplied with 3 * 2 and then adds
into 7.
Precedence of Java Operators (Cont’d)
Precedence of Java Operators (Cont’d)
Java Package

 It is a way of categorizing the classes and interfaces.


 When developing applications in Java, hundreds of classes and interfaces will be
written, therefore categorizing these classes is a must as well as makes life much
easier.
Import Statements

 In Java if a fully qualified name, which includes the package and the class name
is given, then the compiler can easily locate the source code or classes.
 Import statement is a way of giving the proper location for the compiler to find
that particular class.
 For example, the following line would ask the compiler to load all the classes
available in directory java_installation/java/io −

import java.io.*;
Data input in Java

 Data can be inputted using a class called scanner


 Scanner is found in a package file called util.

import java.util.*; //imports all classes in the util package

import java.util.Scanner; //imports the scanner class


Java Scanner class

 The java.util.Scanner class is one of the various ways to read input from the
keyboard.
 It breaks the input into tokens using a delimiter that is whitespace by default.
 It provides many methods to read and parse various primitive values.
 Java Scanner class is widely used to parse text for string and primitive types using
regular expression.
Scanner class methods
Practice Question 1
Write a program to accept any 2 numbers and find sum

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
System.out.println("Enter First Number");
int x = input.nextInt();
System.out.println("Enter second Number");
int y = input.nextInt();

int z = x+y;
System.out.println("The sum of "+x+" and "+y+" is
"+z);
}
More Practice Questions

1. Write a program that accepts 2 integer numbers. Determine and display sum,
difference, product, remainder after division and quotient on the 2 numbers.

2. Write a program that allows user to enter rate and hours worked. Calculate and
display employee salary due

3. Write a program that accepts student marks for 3 subjects. Calculate and
display average mark
The End!!!

You might also like