Java Fundamentals
Java Fundamentals
Java Fundamentals
Contents
❖ Review of Object oriented concepts
❖ Evolution of Java
❖ Comparison of Java with other programming languages Java features, Java and World Wide Web, Java
Run Time Environment. JVM architecture.
❖ Overview of Java Language
❖ Simple Java Program
❖ Java Program Structure.
❖ Installing and Configuring Java.
❖ Java Tokens, Java Statements, Constants, variables, data types.
❖ Declaration of variables, Giving values to variables, Scope of variables
❖ Arrays
❖ Symbolic constants
❖ Typecasting, Getting values of variables, Standard default values
❖ Operators, Expressions, Type conversion in expressions, Operator precedence and associatively
❖ Mathematical functions
❖ Control statements- Decision making & looping.
Department of E & TC
Objectives
Discuss the concept of classes, objects implementation using Java.
Outcome
Apply fundamental Java programming constructs to effectively find
solutions for given computational problems.
Department of E & TC
Java Evolution
The Creation of Java
• Java was conceived by James Gosling, Patrick Naughton, Chris Warth,
Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991.
• It took 18 months to develop the first working version. This language was
initially called “Oak” but it existed so was renamed “Java” in 1995.
• Java Slogan: Java is Everywhere
Department of E & TC
History of Java
• James Gosling initiated the Java language project in June 1991 for use in one of
his many set -top box projects. The language, initially called Oak after an oak tree
that stood outside Gosling's office, also went by the name Green and ended up later
being renamed as Java, from a list of random words.
• Sun released the first public implementation as Java 1.0 in 1995. It promised
Write Once, Run Anywhere (WORA), providing no-cost run- times on popular
platforms.
• On 13 November 2006, Sun released much of Java as free and open
source software under the terms of the GNU General Public License (GPL).
• On 8 May 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.
• The primary motivation was the need for a platform-independent (that is,
architecture neutral) language that could be used to create software to be
embedded in various consumer electronic devices, such as microwave ovens and
remote controls.
Department of E & TC
Job Opportunities
There are various sector where you can go.
• Android developer.
Department of E & TC
Java Applications
• Mobile Applications.
• Web-based Applications.
• Gaming Applications.
• Business Applications.
• App designs
• Web servers.
Department of E & TC
Overview of Java Language
Features of Java Language: Java is,
• Object Oriented: In Java, everything is
an Object. Java can be easily extended since it
is based on the Object model.
• Platform independent: Unlike many other programming
languages including C and C++, when Java
is compiled, it is not compiled
into platform specific machine, rather into platform independent
byte code. This byte code is distributed over the web and interpreted by
Java virtual Machine (JVM) on whichever platform it is being run.
Compiled by
Java Source Interpreter
JavaC
code (JDK)
compiler
Department of E & TC
JVM architecture
❖ Java Virtual Machine (JVM) is a engine that provides runtime environment to drive
the Java Code or applications.
❖ It converts Java bytecode into machines language.
❖ JVM is a part of Java Run Environment (JRE). In other programming languages, the
compiler produces machine code for a particular system.
❖ However, Java compiler produces code for a Virtual Machine known as Java Virtual
Machine.
Load
Link -- Verify,
Prepare
Resolve
Initialise
Department of E & TC
Department of E & TC
1) ClassLoader
The class loader is a subsystem used for loading class files. It performs three major functions viz. Loading,
Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures and the code for methods.
3) Heap
All the objects when created are stored in the heap. Example arrays. This memory is common and shared
across multiple threads.
4) Java Stacks
Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM stack,
created simultaneously as the thread is created. A new frame is created whenever a method is invoked, and it
is deleted when method invocation process is complete.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently executing. In Java,
each thread has its separate PC register.
6) Native Method Stacks
Native method stacks hold the instruction of native code depends on the native library. It is written in
another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems. The test execution engine never
carries any information about the tested product.
8) Native Method interface
The Native Method Interface is a programming framework. It allows Java code which is running in a JVM
to call by libraries and native applications.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution Engine.
Department of E & TC
JAVA VS C
• Java does not include the C unique statement keywords sizeof and
typedef.
• Java does not contain the data types struct and union.
• Java does not define the type modifiers keywords auto, extern, register,
signed, and unsigned.
• Java does not support an explicit pointer type.
• Java does not have a preprocessor and therefore and therefore we cannot use
#define, #include, and #ifdef statements.
• Java requires that the function with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
• Java adds new operators such as instanceof and >>> (right shift operator).
• Java adds labeled break and continue statements.
• Java adds many features required for object oriented programming.
Department of E & TC
JAVA VS C++:
• Java does not support operator overloading.
• Java does not have template classes as in c++.
• Java does not support global variables. Every variable and method is declared
within the class and forms part of that class.
• Java does not use pointers.
• Java has replaced the destructor function with a finalize ()
function.
• There is no header file in java.
Department of E & TC
Java Vs C Vs C++ in terms of execution
• In case of C or C++ (language that are not platform independent), the compiler
generates an .exe file which is OS dependent.
• When we try to run this .exe file on another OS it does not run, since it is OS
dependent and hence is not compatible with the other OS.
• In Java, the main point here is that the JVM depends on the operating system – so if
you are running Mac OS X you will have a different JVM than if you are running
Windows or some other operating system.
Department of E & TC
Overview of Java Language
• JAVA Program Structure:
Department of E & TC
JAVA TOKENS:
Department of E & TC
1. Java Keywords
The following list shows the reserved words in Java. These reserved words may not
be used as constant or variable or any other identifier names.
Department of E & TC 10
2. Identifiers
• Identifiers are programmer defined tokens.
❖ They can have alphabets, digits, and the underscore and dollar sign characters.
Department of E & TC
3. Literals:
• Literals in java are a sequence of characters (digits, letters, and other characters) that
represents constant values stored in variables.
For example :
Department of E & TC
4. Operators:
• An operator is a symbol that takes one or more arguments and operates on them
to produce a result.
• Operators
❖ Arithmetic (+, -,*, /).
❖ Relational (<, <=, >, >=, ==, !=).
❖ Logical (&&, ||, !).
❖ Assignment (=).
❖ Increment and decrement (++, --).
❖ Conditional (?:).
❖ Bitwise (&, |, ^, ~, <<, >>, >>>).
❖ Special (instanceof, dot )
Department of E & TC
5. Separators:
• Separators are symbols used to indicate where groups of code are divided and
arranged.
• They basically define the shape and function of our code. (), {}, [], ;, . , , etc are
Department of E & TC
Symbol Name Usage
• Example:
Integer constant (Decimal, Octal, Hexa):
123 -321 654321
Real Constant: 0.0083 -0.75 735.36
Character Constant: ‘5’ ‘x’ ‘;’ 0
String Constant: “Hello “1997” “5+3”
Java”
Department of E & TC
Type of
Data Type Description Example
Constant
Whole numbers
Integer int int a = 10;
(no decimal)
Single character
Character char char ch = 'A';
(in single quotes)
Group of
String String String name ="Diagram";
characters (text)
True or False
Boolean boolean boolean flag = true;
values
2. Variables:
• The variable is the basic unit of storage in a Java program.
• A variable is defined by the combination of an identifier, a type, and an optional
initializer.
• In addition, all variables have a scope, which defines their visibility, and a lifetime.
These elements are examined next.
• Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of
a variable declaration is shown here:
type identifier[ =value][,identifier[=value] ...] ;
• Here are several examples of variable declarations of various types.
Note that some include an initialization.
✔ int a, b, c; // declares three ints, a, b, and c.
✔ int d = 3, e, f = 5; // declares three more ints, initializing d and f.
✔ byte z = 22; // initializes z.
✔ double pi = 3.14159; // declares an approximation of pi.
✔ char x = 'x'; // the variable x has the value 'x'
Department of E & TC
Scope Of variables:
• Java variables are actually classified into three kinds:
✔ Instance variables.
✔ Class variables, and
✔ Local variables.
• Instance and class variables are declared inside a class. Instance variables are created
when the objects are instantiated and therefore they are associated with the objects.
They take different values for each class creates. Only one memory location is created
for each class variables.
• Variables declared and used inside methods are called local variables. They are
called so because they are not available for use outside the method definition. Local
variables can also be declared inside the program blocks that are defined between an
opening braces { and closing brace }. These variables are visible to program only from
the beginning of its program block to the end of program block. When program control
leaves a block, all the variables in the block will cease to exist. The area of program
where the variable is accessible (i.e. usable) is called its scope.
Department of E & TC cont……. 19
• We can have program blocks within other program blocks (called nesting) as
shown in figure. Each block contains its own set of local variable declarations. We
cannot, however declare a variable to have the same name as one in outer block. In
figure the variable x declared in block1 is available in all three blocks. However,
the variable n declared in block 2 is available only in block 2, because it goes out
of the scope at the end of block 2. Similarly, m is accessible only in block 3.
• Note that we cannot declare the variable x again in block2 and block3 (This is
perfectly legal in C and C++).
Department of E & TC
Type Casting:
• We often encounter situations where there is a need to store a value of one type into
a variable of another type. In such situations, we must cast the value to be stored by
proceeding it with the type name in parentheses. The syntax is:
Department of E & TC
Casts that results in no loss of information
Department of E & TC
Data Types
• Every variable of java has a data type.
• Data type specifies the size and type of values that can
be stored.
• Specify the type of data and the length of the data item
in bytes.
Department of E & TC
Data Types
Department of E & TC
Operators and Expressions:
– Arithmetic Operators
– Relational Operators
– Bitwise Operators
– Logical Operators
– Assignment Operators
– Misc Operators
– Special operators
Department of E & TC
The Arithmetic Operators:
• Arithmetic operators are used in mathematical
expressions in the same way that they are
used in algebra. The following table lists the
arithmetic operators:
• Assume integer variable A holds 10 and variable B holds 20, then
Department of E & TC
The Relational Operators:
• There are following relational operators supported by Java language:
• Assume variable A holds 10 and variable B holds 20, then:
Department of E & TC
The 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
Department of E & TC
The Bitwise
Operators:
Department of E & TC
The Logical Operators:
• The following table lists the logical operators:
• Assume Boolean variables A holds true and variable B holds false, then:
Department of E & TC 30
The Assignment Operators:
There are following assignment operators supported by Java language.
Department of E & TC
31
Misc Operators
• There are few other operators supported by Java Language.
• 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
• Following is the example:
public class Test{
public static void main(String args[])
{
int a , b;
a =10;
b =(a ==1)?20:30;
[Link]("Value of b is : "+ b );
b =(a ==10)?20:30;
[Link]("Value of b is : "+ b );
}
}
• This would produce the following result:
Value of b is:30
Value of b is:20
Department of E & TC
Special operators
instanceof:
class or not.
this statement returns true if person belongs to student else returns false.
Department of E & TC
Operator precedence and associatively
This is very important when there is an expression involving more than one operator.
Rank Operators
1 . , () , []
2 - , ++ , -- , ! , ~
3 *,/,%
4 +,-
5 << , >> , >>>
6 < , <= , > , >= , instanceof
7 == , !=
8 &
9 ^
10 `
11 &&
12 `
13 ?: (ternary operator)
14 =
Department of E & TC
Java Decision Making
• There are two types of decision making statements in Java.
They are:
✔ if statements
✔ switch statements
The if Statement:
• An if statement consists of a Boolean expression followed by
one or more
statements.
• Syntax:
The syntax of an if
statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
•
Department of E & TC 34
• Example:
public class Test{
public static void main(String
args[]){ int x =10;
if( x <20){
[Link]("This is if statement");
}
}
}
}
}
Department of E & TC
• Example:
• public class Test {
public static void main(String[] args) {
int day = 3;
switch(day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
default:
[Link]("Invalid day");
}
}
}
Loop Statements :
1. while ( <condition>)
{
------------------- //loop body
}
2. for( <initialization>; <condition testing>; <increment/decrement> )
{
------------------- //loop body
}
3. do
{
------------------- //loop body
} while ( <condition>);
Department of E & TC
public static void main(String argc[])
Public:
This is an access modifier. It has to be public so that java runtime can execute this method. Remember that if you
make any method non-public then it’s not allowed to be executed by any program, there are some access
restrictions applied
Static:
In any Java program, the main() method is the starting point from where compiler starts program execution. So,
the compiler needs to call the main() method.
If the main() is allowed to be non-static, then while calling the main() method JVM has to instantiate its class.
Static method of a class can be called by using the class name only without creating an object of a class.
The main() method in Java must be declared public, static and void. If any of these are missing, the Java
program will compile but a runtime error will be thrown.
Void:
Main() method does not return any thing thus it is void.
String argc[]:
This is a command line arguments (Input). These are passed to the program during runtime. These arguments
are passed as arguments to main(String args[]).
This means that arguments are stored in array args[] and are of String datatype.
final keyword in java
final keyword is applicable only to a variable, a method or a class
❖ Declaring an array
Arrays are dynamically allocated.
Arrays are treated as objects and thus can find their length using member length.
❖ Declaration of an array
int [ ]a;
int a[ ];
int a[ ] = {10,20,30,40};
string s[ ] = {“abc”,”pqr” };
for(i=0;i<[Link];i++)
{
[Link](a[i])
}
Department of E & TC
For-each Loop for Java Array
❖ We can also print the Java array using for-each loop.
❖ The Java for-each loop prints the array elements one by one.
❖ It holds an array element in a variable, then executes the body of the loop.
❖ The syntax of the for-each loop is given below:
for(data_type variable : array)
{
//body of the loop
}
Example:
class Testarray
{
public static void main(String args[])
{
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
[Link](i);
}
}
Department of E & TC
Programs:
❖ Write a program to find factorial of a number.
package factorial;
public class Factorial {
public static void main(String[] args) {
int i, fact =1, n = 4;
for(i=1;i<=4;i++)
{
fact = fact*i;
}
[Link]("Factorial is: "+fact);
}}
❖ Write a program to print elements in an array.
package array;
public class Array_print {
public static void main(String[] args)
{
int a[] = {10,12,13,14};
int i;
[Link]("The elements in array are:");
for(i=0;i<[Link];i++)
{
[Link]("\t"+a[i]);
}
}} Department of E & TC
Mathematical functions in java
Java supports many mathematical functions through class math.
This math class is defined in package called [Link]
Syntax:
Math.function_name()
Example:
[Link](x,y);
This method finds the max out of x and y.
List of functions:
❖ max(x,y)
❖ min(x,y)
❖ sqrt(x)
❖ abs(x) absolute (positive) value of x. Thus x should be negative.
❖ random() This method returns randomly numbers between 0 and 1
❖ sin(x)
❖ cos(x)
❖ tan(x)
❖ pow(x,y) returns x^y
❖ exp(x) returns e^x
Department of E & TC
Reading Input from User
❖ Java Scanner class allows the user to take input from user.
❖ It belongs to [Link] package.
❖ It is used to read the input of primitive types like int, double, long, short, float, and byte. It
is the easiest way to read input in Java program.
❖ To use Scanner class we have to create an object of that class and import the class in our
program.
❖ Syntax:
import [Link];
Scanner object_name=new Scanner([Link]);
❖ Example:
Scanner obj1 = new Scanner([Link])
This will create a object of class scanner. There are different methods (Functions in this class
which are now accessed using the object. JDK
Example: Package1 package2
Department of E & TC
Methods of Java Scanner Class
Java Scanner class provides the following methods to read different primitives types:
Method Description
int nextInt() It is used to scan the input as an integer.
Department of E & TC
Programs
Write a program to add two numbers
package add_user;
import [Link];
Department of E & TC
Programs
Write a program to print name, age and salary of an employee.
package person;
import [Link];
public class Person {
} Department of E & TC
Programs
Write a program to print day in a week.
package dayinaweek;
import [Link];
public class Day {
Department of E & TC