Lesson 2 - Java Programming Fundamentals
Lesson 2 - Java Programming Fundamentals
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
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.
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.
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.
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.
After compiling when you will try to run the byte code(.class file), the
following steps are performed at runtime:-
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.
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
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.
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.
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.
}
Displaying a Single Line of Text with Multiple Statement
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
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.
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.
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.
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
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
class Vehicle {}
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
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
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!!!