Module - 1 Fundamentals
Module - 1 Fundamentals
Module – 1:
Chapter – 1: Java Programming Fundamentals Chapter – 2: Introducing Data Types and Operators
1.1 The Java Language 2.1 Java’s Primitive Types
1.2 The Key Attributes of OOP 2.2 Literals
1.3 The Java Development Kit 2.3 A Closer Look at Variables
1.4 A First Simple Program 2.4 The Scope and Lifetime of Variables
1.5 The Java Keywords 2.5 Operators
1.6 Identifies in Java 2.6 Shorthand Assignments
1.7 The Java Class Libraries 2.7 Type conversion in Assignments using Cast
2.8 Operator Precedence
2.9 Expressions
Chapter – 3: Program Control Statements Chapter–4: Introducing Classes, Objects & Methods
3.1 Input characters from the Keyword 4.1 Class Fundamentals
3.2 Control Statements: 4.2 How Objects are Created
if, Nested ifs, if-else-if Ladder, 4.3 Reference Variables and Assignment
Switch Statement, Nested switch 4.4 Methods, Returning from a Method
for Loop, Enhanced for Loop,
While Loop, do-while Loop, 4.5 Returning Value
Use break, Use continue, 4.6 Constructors
Nested Loops 4.7 The new operator Revisited
4.8 Garbage Collection and Finalizers
4.9 The ‘this’ Keyword
Chapter – 5: More Data Types & Operators Chapter – 6: String Handling
6.1 String Fundamentals
5.1 Arrays and Alternative Array
6.2 The String Constructors
Declaration Syntax
6.3 Three String-Related Language Features
5.2 Multidimensional Arrays
6.4 The Length() Method
5.3 Assigning Array References
6.5 Obtaining the characters within a string
5.4 Using the Length Member
6.6 String Comparison
5.5 For-Each Style for Loop
6.7 using indexOf() and lastIndexOf()
5.6 Strings
6.8 Changing the case of characters within a
string
6.9 StringBuffer and String Builder
Prepared by
Mrs. Suma M G
Assistant Professor
Department of MCA
RNSIT
Bengaluru – 98.
20MCA22 Module-1
Chapter-1
Java Programming Fundamentals
2. Gosling decided that he would develop his own, simplified computer language to avoid all the problems
faced in C++.
3. Gosling kept the basic syntax and object oriented features of the C++ language to designing a new language.
5. Later Sun Microsystems was discovered that the name “OAK” was already claimed, they changed the name
to “JAVA” in 1995.
6. The Java team realized that the language they had developed would be perfect for web programming because
the World Wide Web had transformed the text-based internet into a graphic rich environment. Then team
came up with the concept of web applets, small programs that could be included in web pages, and even
went so far as to create a complete web browser that demonstrate the language’s power.
7. The new language was quickly embraced as a powerful tool for developing internet applications. Support
for java was added in the Netscape (Web Browser on UNIX) and in the Internet Explorer.
Java applets:
An applet is a special kind of java program that is designed to be transmitted over the Internet and automatically
executed by java web browser.
Security
Java achieved this protection by confining an applet to the java execution environment and not to allowing it
access to other parts of the computer.
Features of JAVA:
1. Simple: Syntax is based on C and C++. But No pointers, No goto, No operator overloading,
No Pre-processors, No global variables.
2. Object-Oriented: Uses OOPs concepts (Inheritance, Polymorphism, Encapsulation, etc)
5. Robust:
• Java uses the automatic garbage collection that prevents memory leaks.
• Java is strictly typed language, hence Error free.
6. Dynamic:
• Java loads in classes as they are needed.
• JVM is capable of linking dynamic new classes, methods and objects.
8. High Performance:
• Byte code are highly optimized.
• JVM execute Byte code much faster.
10. Multithreaded:
Encapsulation:
It is a mechanism that binds together code and the data it manipulates, Example:
and that keeps both safe from outside interference and misuse. In class Employee {
int eid;
encapsulation, the variables of a class will be hidden from other classes, string name;
and can be accessed only through the methods of their current class. float salary
void read();
Therefore, it is also known as data hiding. int getSalary();
}
Polymorphism:
Inheritance:
Byte code loaded into JVM ➢ It contains classloader, memory area, execution
engine etc.
At Runtime time
Main task of JVM:
Java Virtual Machine 1. Search and locate the required files.
JIT JAVA Interpreter
2. Convert byte code into executable code.
3. Allocate the memory into ram
4. Execute the code.
Operating System
5. Delete the executable code.
Figure 1.2: JVM Diagram
Unix Running
JVM
Macintosh Running
JVM
Figure 1.3: How Java compiler converts Java source into Java bytecodes
The Java compiler reads Java language source (*.java) files, translates the sources into Java bytecode and places
the bytecodes into class (*.class) files. The compiler generates one class file per class in the source.
JRE (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 (JRE) provides the libraries, the Java
Virtual Machine, and other components to run applets and applications
written in the Java programming language. JRE does not contain tools
and utilities.
This command will call the Java Compiler asking it to compile the specified file. If there are no errors in the
code the command prompt will take you to the next line.
Primitive datatypes are predefined by the language and named by a keyword. Primitive values do not share state
with other primitive values.
Non-Primitive datatypes are reference/objects types such as classes, interface, string, arrays etc,. Default value
of any reference variable is null.
The following table summarize the default values, size and range for the built-in data types.
Table 2.1: Java’s built-in data types description
Type Contains Default Size Range
boolean True or false False 1 bit NA
byte Signed integer 0 8 bits -128 to 127
char Unicode Character ‘\u0000’ 16 bits \u0000 to \uFFFF
double IEEE 754 floating point 0.0d 64 bits +4.9E –324 to +1.7976931348623157E+308
float IEEE 754 floating point 0.0f 32 bits +1.4E – 45 to + 3.4028235E+38
int Signed Integer 0 32 bits -2147483648 to 2147483647
-9223372036854775808 to
long Signed Integer 0L 64 bits
9223372036854775807
short Signed Integer 0 16 bits -32768 to 32767
Note: Java defines four integer types: byte, short, int, and long
Note:
❖ an int variable cannot turn into a char variable
❖ All the variables in java must be declared prior to their use
❖ The type of the variable cannot be change during its lifetime
Initializing a Variable:
A variable must be declared before to their use. This is necessary because the compiler must know what type of
data or value that can contains it use.
At the time of declaration, we can initialize the value to the variable by using assignment operator as shown
here:
type var_name = value; Where, value - is the value that is to var when var is
created. Value is known at compile time
Types of variables:
➢ Local variables – inside method
➢ Instance variables - common to class methods.
➢ Class variables – are static variables
➢ Reference variable – hold some reference
class Person{ Instance Variable
string name;
static int count; Class variable
void fun( ) {
int data;
Local variable
//other code
}
public static void main(String[] args){
Person p; Reference variable
p=new Person();
p.fun();
Creates dynamic object
} }
++ Increment irem=10%3;
-- decrement
dresult=10.0/3.0;
drem=10.0%3.0;
System.out.println("Result&remainder:"
+iresult + "\t" +irem);
System.out.println("Result&remainder:"
+dresult + "\t" +drem);
}
}
== Equal to class RelDemo{
public static void main(String[] args){
!= Not equal to int i=10, j=11;
Relational
^ if(i= =j)
OR)
Short-circuit System.out.println("Equal");
|| else
OR
Short-circuit System.out.println("NotEqual");
&& }
AND
}
! NOT
• A short circuit operator is one that doesn't necessarily evaluate all of its operands.
• expr1 && expr2 represents a logical AND operation that employs short-circuiting behaviour. That is,
expr2 is not evaluated if expr1 is logical false.
Note: The difference between the normal (&, |) and short-circuit (&&, ||) versions
✓ The normal operands will always evaluated each operand
✓ The short-circuit version will evaluate the second operand only when necessary.
Example: x = x + y; Equivalent to x += y;
to
The operator pair += tells the compiler to assign x the value of x plus y. The shorthand will work for all the
binary operators in Java.
Syntax: var opr= expression;
Thus, the arithmetic and logical shorthand operators are the following: += -= *= /=
%= &= |= ^=
Bitwise Operator:
➢ are used to test, set, or shift the individual bits that make up a value.
➢ can be applied to values of type long, int, short, char, or byte.
➢ cannot be used on Boolean, float or double or class type.
Table 2.3: List of Operators and example (continued)
Operators &
Category Description Example
Meaning
& class UpLwDemo{
Bit by bit evaluated
Bitwise AND public static void main(String[]args)
| {
Bit by bit evaluated
Bitwise OR char ch;
^ for(int i=0; i<10; i++)
Bit by bit evaluated
Exclusive OR {
>> sign bit is shifted in ch=(char) ('A' + i);
Signed Shift high-order System.out.print(ch);
Bitwise
right positions.
>>> Zero’s are shifted in ch=(char) ((int) ch | 32);
Unsigned high-order System.out.print(ch + " ");
Shift right positions.
Zero’s are shifted in }
<<
Low-order }
Left shift
positions.
}//Uppercase to Lowercase
~ Output:
One’s One’s complement Aa Bb Cc Dd Ee Ff Gg Hh Ii Ji
complement
?: Ternary or
Miscellaneous
b = (a == 1) ? 20: 30;
conditional
instanceof The operator checks
whether the object is String name = "James";
of a particular type boolean result=name instanceof String;
System.out.println( result );
Shift operator:
Java defines the 3 shift-operators shown here:
<< Bits are moved left by the number of bits specified by the right operand and 0 bits are
(Left Shift) filled on the right.
>> Bits are moved right by the number of bits specified by the right operand and preserves
(Right Shift) the signed bit that means shifted values filled up with 1 bits on the right.
>>> Bits are moved right by the number of bits specified by the right operand and shifted
(Unsigned
values are filled up with zeros. It is also called as Zero – fill right shift.
right shift)
Implicit Type:
An implicit conversion means that a value of one type is changed to a value of another type automatically.
Automatic type casting take place when,
• The two types are compatible
• The target type is larger than the source type.
The lower size is widened
to higher size. This is also
named as automatic type
conversion or widening.
Explicit Type:
Explicit conversions are done via casting. When you are assigning a larger type value to a variable of smaller
type, then you need to perform explicit type
casting. It is called as explicit conversion or
narrowing conversion and there may be data loss
in this process because the conversion is forceful.
2.10. Expressions
Operators, variables, and literals are components of expressions.
Type Conversion in expressions:
• Possible to mix 2 or more compatible different data types.
• they are all converted to the same type.
• Java’s type promotion rules can be used for the conversion in an expression.
Example: 2 + (5.0*2.0) -3;
char ch= (char) (ch1 + ch2);
class ExprDemo{ Note: Java’s type Promotion Rules
public static void main(String[] args){ ➢ All char, byte and short values are
byte b; promoted to int.
int i; ➢ Any one operand is a long, the
b=10; whole expression is promoted to long
i = b * b; //No cast needed
b=10; ➢ Any one operand is a float, the whole
b=(byte) (b * b); // cast is needed expression is promoted to float
➢ Any one operand is a double, the
System.out.println("i=" +i + "b=" +b); result is double.
}
}
Output:
1. InputStreamReader class:
▪ Can be used to read data from keyboard.
▪ Converts Byte stream to character stream.
Syntax:
InputStreamReader ir=new InputStreamReader(System.in);
2. BufferedReader class:
can be used to read data line by line
Syntax:
BufferedReader input = new BufferedReader(ir);
Example 3.3:
class ScannerTest {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno = input.nextInt();
//Statements if(age>18){
} System.out.print("Age is greater
The Java if statement tests the
than 18");
condition. It executes if block if
condition is true. }
if(condition){
//Statements int number=13;
}else{ if(number%2==0){
2. if-else
Statements; System.out.println(“greater”);
} }
... else if (basic > 5000)
else{ sal = basic – tax;
Statements; else
}
sal = basic;
The if-else-if ladder statement executes
one condition from multiple statements.
if (condition){ int a=15, b=20, c=18, big;
if (condition){ if (a>b){
4. nested if
Statements; if (a>c) {
} big = a;
} }
You can use one if or else if statement }
inside another if or else if statement(s).
Iteration Statements:
A loop statement allows us to execute a statement or group of statements multiple times.
Table3.3: Types of Iteration Statements
Type Syntax and Explanations Example
} System.out.println(i);
Repeats a statement or group of statements while a given i++;
condition is true. It tests the condition before executing the
}
loop body.
Output: 1 2 3 4 5 6 7 8 9 10
do{ int i=1;
Statements; do{
2. do-while
}while(condition); System.out.println(i);
Like a while statement, except that it tests the condition at i++;
the end of the loop body. }while(i<=10);
Output: 1 2 3 4 5 6 7 8 9 10
for(initialization;condition;incr/decr) for(int i=1;i<=10;i++){
{
3. for loop
System.out.println(i);
Statements;
}
}
Execute a sequence of statements multiple times and Output: 1 2 3 4 5 6 7 8 9 10
abbreviates the code that manages the loop variable.
for(int i:arr){
}
System.out.println(i);
• for-each loop is used to traverse array or collection in
java. }
• It is easier to use than simple for loop because we don't
need to increment value and use subscript notation. Output: 12 23 44 56 78
• It works on elements basis not index. It returns element
one by one in the defined variable.
Jump Statements:
Loop control statements change execution from its normal sequence.
Table 3.4: Types of Jump Statements
Type Syntax and Explanations Example
}
• It continues the current flow of the program System.out.println(i);
and skips the remaining code at specified }
condition.
Output: 1 2 3 4 6 7 8 9 10
• In case of inner loop, it continues only inner
loop
return false;
method, and control flow returns to where the
method was invoked. return true;
}
• The return statement has two forms: one that
returns a value, and one that doesn't.
if( i==1 )
• The presence of a label will break one;
transfer control to the start of the if( i==2 )
code identified by the label. break two;
if( i==3 )
break three;
}System.out.println(“End Three”);
} System.out.println(“End Two”);
} System.out.println(“End One”);
} // end for
Output:
End One
End Two
End One
End Three
End Two
End One
jump-statement; int a[][]={{1,1,1},{2,2,2},{3,3,3}};
continue label or continue as a form
System.out.println("Element is:"
+ a[i][j]);
}
}
Output:
Element is: 2
Element is: 3
Element is: 3
Nested Loops:
• one loop can be nested inside of another loop.
• used to solve a wide variety of programming problems and are an essential part of programming.
Example:
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print(j+" ");
}
}
Example:
class Student{ A class definition creates a new data type. In
String name="John"; this case, the new data type is called Student.
int sem=3;
void display(){
System.out.print("Name: " +name);
System.out.print("Sem: " +sem);
}
}
Example:
Student std; // declaring reference
OR Student std=new Student();
std=new Student();// creating object of Student
In general, the dot(.) operator is used to access both instance variables and methods as shown below:
Example 4.1:
class Student{ public static void main(String[] a)
String name="John"; {
int sem=3; Student std=new Student();
void display(){ std.name=”Smith”;
System.out.print("Name:" +name); std.sem=5;
System.out.print("Sem:" +sem); std.display()
} }}
4.4 Methods:
A methods contains the statements that define its actions.
• Each method has a name and performs only one task
• It is the same name used to call the method
return value;
4.7 Constructors:
It is a special type of method that is used to initialize the object and invoked at the time of object creation.
Syntax:
public ClassName(parameter-list)[throws Exception..]
{
//statements...
}
Characteristics of constructor
• has the same name as its class name
• no explicit return type; not even void
• allocate the space for the object
• can be overloaded
• The modifier of the constructor should not be static (because constructors will be called each and every
time whenever an object is created)
• are not inherited
Types of Constructors
1. Default constructor
2. Parameterized constructor
Parameterized constructor:
A constructor that have parameters is <class_name>(parameter list){
known as parameterized constructor. //code
It provides different values to distinct
}
object.
Example 4.2:
class Student{
String name;
int id;
//Default Constructor
Student(){
System.out.println("Default Constructor and Initialize
Default Value");
}
//Parametrized Constructor
Student(String name1, int id1){
System.out.println("Parameterized Constructor and Initialize
given Value");
name=name1;
id=id1;
}
void display() {
System.out.println("Name= " + name + "\n" + "ID= " +id);
}
public static void main(String[] args){
//call default Constructor
Student std=new Student();
std.display();
//call Parametrized Constructor
Student std1=new Student("James", 101);
std1.display();
}
}
a1 = a2;
System.out.println("done");
a1.finalize();
//System.gc();
}
}
5.1 Arrays:
Array is collection of variables of the same type, referred to by a common name that have contiguous memory
location.
• Array is an object that contains elements of similar data type.
• It is a data structure where we store similar elements. We can store only fixed set of elements in java
array
• Array is index based; first element of the array is stored at 0 index.
Advantage of Java Array
• Code optimization: It makes code optimized, we can retrieve or sort the data easily.
• Random access: We can get any data located at any index.
Disadvantage of Java Array
• Size Limit: We can store fixed size of elements in the array. It does’t grow its size at runtime. To
solve the problem, collection framework is used in java.
Types of Array
i. Single dimensional or one dimensional
ii. Two or Multidimensional
iii. Irregular
type[] array_name;
or In Single Line, declaration and allocation
type array_name[]; type[] array_name=new type[size];
Example:
int[] a;//creates array object
a= new int[10]; //allocate memory for 10 integer element
int[] b = new int[5];//creating and allocating memory for 5 integer element has done in
single line
array_name=new type[row][col];
Initialization
A two-dimensional array can be initialized by enclosing each dimension’s initializer list within its own set of
braces.
for(int i=0;i<2;i++){
for(int j=0;j<2;j++)
System.out.print(table[i][j] + " ");
System.out.println("\n");
}
}
}
table[0][0]=1;
table[0][1]=2;
table[0][2]=3;
table[1][0]=4;
for(int i=0;i<table.length;i++){
for(int j=0;j<table[i].length;j++)
System.out.print(table[i][j] + " ");
System.out.println("\n");
}
}
}
class UpCase {
public static void main(String args[]) {
char ch;
for(int i=0; i < 10; i++){
ch = (char) ('a' + i);
System.out.print(ch);
ch = (char) ((int) ch & 65503);
System.out.print(ch + " ");
}
}
}
String Handling
Constructing String:
String can be created using:
➢ String Literal ➢ String constructor
String Literal:
▪ Strings are maintained in String literal Pool of a Heap
▪ String literal Pool is a pool of unique Strings(avoids String str=“Hello”;
duplicate string object )
Whenever compiler encounters a string literal, it creates a String object with given string value.
JVM performs String pool check with following actions
❖ first checks String pool for the string literal.
❖ If the literal is exist, return its reference.
❖ If literal not exist, create the new literal in pool.
Example:
str1 str1
Hello
Hello
str2 str2
Hi
Common pool Common pool
SN Constructors Example
1 String(): String s1=new String();
Initializes a newly created String object so that it represents
an empty character sequence.
2 String(byte[] bytes): byte[] b={‘h’,‘e’,‘l’,‘l’, ‘o’};
Constructs a new String by decoding the specified array of String s=new String(b);
bytes using the default charset of the platform.
3 String(byte[] bytes, int offset, byte[] b={‘h’,‘e’,‘l’,‘l’, ‘o’};
int length): String s=new String(b,1,3);
Constructs a new String by decoding the specified subarray
of bytes using the platform’s default charset. Starting from
offset, length number of characters is taken from byte array.
4 String(char[] ch): char[] ch={‘h’,‘e’,‘l’,‘l’, ‘o’};
allocates a new string, it represents the sequence of character. String s1=new String(ch);
class StrDemo{
Example 6.1: public static void main(String[] args){
String s1="Welcome to Bengaluru";
System.out.println("s1= "+s1);
String s2=new String();
System.out.println("s2= " +s2);
String s3=new String("Welcome to Bengaluru");
System.out.println("s3= " +s3);
byte[] b={'h','e','l','l','o'};
String s4=new String(b);
System.out.println("s4= "+s4);
byte[] b1={'c','o','l','l','e','g','e'};
String s5=new String(b1,1,4);
System.out.println("s5= " +s5);
char[] ch={'h','e','l','l','o'};
String s6=new String(ch);
System.out.println("S6= " +s6);
char[] ch1={'w','e','l','c','o','m','e'};
String s7=new String(ch1, 1, 3);
System.out.println("S7= "+s7);
}
}
4. Overriding toString():
Represent any object as a string using toString() method. It returns the string that describes the object.
By overriding the toString() method of the Object class, we can return values of the object, so we don't need to
write much code.
public String toString( ) { // overriding
Example:
return rollno + “ “+ name;
}
public static void main(String[] args){
Student s =new Student(101,”Anil”);
System.out.println(s);
}
equals( ) vs = = operator
• equals( ): Compares the characters inside a String object.
• The = = operator compares the references to see whether both refer to the same instance.
String s1 = new String ("ABC");
Example
String s2 = new String ("ABC");
System.out.println(s1.equals(s2) ); // true
System.out.println( s1==s2 ); //false
• StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is
synchronized.
SN Methods SN Methods
append(): Overloaded setlength():
1 10
change the size of the StringBuffer object
capacity(): lastIndexOf()
2 11
Returns the current capacity of StringBuffer returns the last occurrence position
trimTosize(): indexOf():
3 12
Deleting the whitespace in the string returns the first occurrence position
delete(): replace():
4 13
delete the characters within the range character can be replaced in the object
deleteCharAt(): reverse():
5 14
delete a character at given position return the reversed string
ensureCapacity() setCharAt()
6 15 Changes a character at specified index in
returns the length of the string
StringBuffer object
toString()
7 insert(): Overloaded 16 Overloaded. Converts StringBuffer object to
string object
length(): getchars()
8 17
returns the length of the object returns sequence of characters
charAt(): substring()
9 18
returns the character at specified index Overloaded
Example 2: Write program to check email belongs to which domain (like: gmail, yahoo,rediff .etc)
class Demo {
public static void main(String args[]){
String email = "[email protected]";
i. >>>
ii. Left shift
iii. Bitwise operators
iv. &&
v. Right Shift
3. Program Control Statements
1. What are the ways input characters from the keyboard? Explain
2. Discuss the Conditional Statements (all if statements) with an example.
3. Explain different types of Iteration Statements (while, do-while, for) and Jump Statements
( break, continue) with an example.
4. Explain for-each loop with an example.
5. Explain multi-way conditional statement (switch) with syntax. Give an example
6. Explain usage of break with label and continue with label with an example.
3. What are Irregular array? Write a program to find the sum of all the elements in an Irregular array.
4. Write a short note on length member in an array.
6. String Handling
1. What is String? Explain different types of String Constructors.
2. Read all types of methods to modify the string object.
3. Differences between String Buffer and String
4. Differences between String Literal and String Object.
Programs List
1. Write a program to convert from uppercase to lowercase using bitwise operator.