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

Module - 1 Fundamentals

The document discusses an Object Oriented Programming course with Java. It covers key chapters including Java fundamentals, data types, control statements, classes and objects, methods, and string handling. The main topics are: 1. The history and features of Java, including its simplicity, portability, security, and object-oriented nature. 2. Core Java concepts like encapsulation, polymorphism, and inheritance which are supported through classes, objects, and methods. 3. Data types and operations in Java including primitive types, literals, variables, operators, arrays, and strings. 4. Program control statements for input/output, conditionals, and loops.

Uploaded by

Vijay V
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Module - 1 Fundamentals

The document discusses an Object Oriented Programming course with Java. It covers key chapters including Java fundamentals, data types, control statements, classes and objects, methods, and string handling. The main topics are: 1. The history and features of Java, including its simplicity, portability, security, and object-oriented nature. 2. Core Java concepts like encapsulation, polymorphism, and inheritance which are supported through classes, objects, and methods. 3. Data types and operations in Java including primitive types, literals, variables, operators, arrays, and strings. 4. Program control statements for input/output, conditionals, and loops.

Uploaded by

Vijay V
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Object Oriented Programming with JAVA [20MCA22]

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

1.1 History of JAVA:


1. In 1990, James Gosling was given a task of creating projects to control consumer electronics. Gosling and
his team Mike Sheridan, and Patrick Naughton at Sun Microsystems started designing their software using
C++ because of its Object-oriented nature. Gosling, however, quickly found that C++ was not suitable for
this project. They faced problems due to program bugs like memory leak, dangling pointer, multiple
inheritance and platform dependent.

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.

4. He completed and named “OAK” in 1991 at Sun Microsystems.

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’s Contribution to the Internet:


➢ Java in turn had a profound effect on the internet.
➢ Java innovated a new type of networked program called applet.
➢ Java also addresses some issue like portability, Security, JVM.

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.

Mrs. Suma M G, AP, MCA, RNSIT 1 | 45


20MCA22 Module-1
Benefits of Using JAVA:
• Java programming language is very simple and easy to learn. It is object oriented.
• Java applications run inside JVM, and now all major operating systems are able to run Java including
Windows, Mac and UNIX.
• Write once, run anywhere: A Java application runs on all Java platforms.
• Java is very secure. Only Java applications that have permission can access the resources of the main
computer. Thus, the main computer is protected from virus attackers and hackers.
• Java technologies have been improved by community involvement. It is suitable for most types of
applications, especially complex systems that are used widely in network and distributed computing.

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)

3. Portable - Platform Independent – Architecture Neutral :


• “Write once, Run anywhere”
• Runs on any platform that has JVM

4. Secured: No explicit pointer, Programs run inside JVM.

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.

7. Compiled and Interpreted:


• Java code is compiled to byte code.
• Byte code are interpreted on any platform by JVM.
• Java programs can be shared over the internet.

8. High Performance:
• Byte code are highly optimized.
• JVM execute Byte code much faster.

9. Distributed: Java programs can be shared over the internet

10. Multithreaded:

• Multithreading means handling more than one job at a time.


• The main advantage of multi-threading is that it shares the same memory.

Mrs. Suma M G, AP, MCA, RNSIT 2 | 45


20MCA22 Module-1
1.2 The Key Attributes of Object-Oriented Programming:
Object oriented programming took the ideas of structured programming and combined them with several new
concepts. In the most general sense, a program can be organized in one of two ways:
• Around its code (What is happening)
• Around its data ( What is being affected)
To support the principles of OOP, all OOP languages, including java, have 3 traits in common:
1. Encapsulation 2. Polymorphism 3. Inheritance

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:

It is derived from 2 greek words: “poly” and “morphs”.


The word “poly” means many and “morphs” means forms.
So polymorphism means many forms. It is defined as that
allows one interface to access a general class of actions or
same name different operations.

Inheritance:

Inheritance can be defined as the process


where one class acquires the properties
(methods and fields) of another.
This is important because it supports the
concepts of hierarchical classification.
Without the use of hierarchies, each object
would have to explicitly define all of its
characteristics.

Using inheritance, an object need only define


those qualities that make it unique within its class. It can inherit its general attributes from its parent. Thus, it is
the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case.

Mrs. Suma M G, AP, MCA, RNSIT 3 | 45


20MCA22 Module-1
1.3 The Java Development Toolkit(JDK):
JDK is provided by Sun Microsystem which is used to develop applications in Java. JDK contains set of libraries,
APIs and Java Virtual Machine (JRE). A complete package to develop and run Java based applications and
applets.
JDK = JRE + Development Tools
JDK is collection of tools like.
Set of Libraries Javac
• To compile - javac Ex: rt.jar, etc
JVM Java
• To execute - java
Other Files etc.,
• To document - javadoc.
• appletviewer Development
Tools
• jar
JRE
Figure 1.1: JDK Toolkit Contains
JVM(Java Virtual Machine):
➢ JVM stands for Java Virtual Machine.
At Compile time
➢ JVM is a part of JRE (Java Runtime
Environment) to execute java byte code(*.class).
JAVA JAVA Compiler Byte Code
Source Code ➢ The use of the same byte code for all JVMs on all
*.class
platforms make java platform independent.

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

JIT or Just-in-time compiler:


• JIT is a part of the JVM.
• It converts the selected portions of bytecode are compiled into the native machine code in order to speed
up the execution time.
• In JVM, Java code is compiled to bytecode. This bytecode gets interpreted on different machines, hence
java is both compiled as well as interpreted language.

Mrs. Suma M G, AP, MCA, RNSIT 4 | 45


20MCA22 Module-1
What are Java Bytecode?
Bytecode is a machine language of the JVM and is a highly optimized set of instructions designed to be executed
by the JVM. Later bytecode translated into native code. Windows
Running JVM

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.

1.4 A First Simple Program:


Let us look at a simple java program.
class Example{
public static void main(String[] args)
{
System.out.println("Welcome to JAVA Class!!!");
}
}
Where,
❖ class: class keyword is used to declare classes in Java
❖ public: It is an access specifier. Public means this method is visible to all.
❖ static: static is again a keyword used to make a method static. To execute a static method you do not
have to create an Object of the class. The main() method here is called by JVM, without creating any
object for class.
❖ void: It is the return type, meaning this method will not return anything.
❖ main: main() method is the most important method in a Java program. This is the method which is
executed, hence all the logic must be inside the main() method. If a java class is not having a main()
method, it causes compilation error. Multiple main() methods in the same class not allowed .
❖ String[] args: This represents an array whose type is String and name is args.
❖ System.out.println: This is used to print anything on the console like printf in C language.

Mrs. Suma M G, AP, MCA, RNSIT 5 | 45


20MCA22 Module-1
You will follow these 3 steps to execute the java program:
i. Enter the program ii. Compile the program iii. Run the program

i. Enter the program:


Open a text editor and write the code as above. Then save the file as Example.java

ii. Compile the program


Open command prompt and go to the directory where you saved your java program. Then, you must compile
it using javac as shown here: javac Example.java

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.

iii. Run the program


To run the program, you must use java. Now type as shown here: java Example
on command prompt to run your program. Then, you will be able to see Welcome to Java Class!!! printed
on your command prompt.

1.5 Handling Syntax Errors:


If you enter something incorrectly into your program, compiler will report a Syntax error messages.
Example: class Example{
public static void main(String[] args) {
System.out.println("Welcome to JAVA Class!!!")
}
}

When you compiled, it will


report a syntax error message
that

1.6 The Java Keywords:


In the Java programming language, 50 keyword or reserved words are currently defined that have a predefined
meaning in the language; because of this, programmers cannot use keywords as names for variables, methods,
classes, or as any other identifier.

Mrs. Suma M G, AP, MCA, RNSIT 6 | 45


20MCA22 Module-1
➢ The keywords const and goto are reserved but not used.
➢ In addition to the keywords, java reserves the following: true, false and null. These are values defined by
java.
➢ assert added in 1.4 and enum added in 1.5

1.7 Identifiers in Java:


An identifiers is a name given to a method, variable, or any other user-defined item that you want to identify in
program.
Rules: • Can have one to several characters
• Variable names should begin with a letter(A-Z, a-z), an underscore(_), a dollar sign($)
• A keyword cannot be used as an identifier.
• Cannot start with a digit but digits can be used after first character.
• Most importantly identifiers are case sensitive

Valid Example: age, $salary, _value, __1_value, my_var, sample123, maxLoad


Invalid Example: 123abc, -salary, super, this

1.8 The Java Class Libraries:


The Java Class Library (JCL) is a set of dynamically loadable libraries that Java applications can call at run time.
Because the Java Platform is not dependent on a specific operating system, applications cannot rely on any of
the platform-native libraries.

Mrs. Suma M G, AP, MCA, RNSIT 7 | 45


20MCA22 Module-1
Chapter-2

Introducing Data Types and Operators

2.1. Java’s Primitive Types:


Java contains two general categories of built-in data types as shown here:

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

Mrs. Suma M G, AP, MCA, RNSIT 8 | 45


20MCA22 Module-1
2.2. Literals:
Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values
to be stored in variables.
Important points: • also commonly called constants
• Java literals can be any of the primitive data types
• Character constants are enclosed in single quotes

Types of literals in java with example as shown here.


Table 2.2: Types of literals

Type Sub Type Representation Example


Decimal Default 123
Octal Prefix: ‘0’ (Zero) 0123
Integer Hexadecimal Prefix: ‘0x’ or ‘0X’ 0x123
Binary Prefix: ‘0b’ or ‘0B’ 0b1100
long Prefix: ‘l’ or ‘L’ 123L
float Postfix: ‘f’ or ‘F’ 40.33f
Floating Default - Postfix:
double
‘d’ or ‘D’
Character Single quote: ‘ ’ ‘a’, ‘:’, ‘\n’, ‘\b’, ‘r’, ‘\f’, ‘\t’, ‘\ddd’, ‘\uxxx’
String Double quote: “ ” “HELLO”
Boolean True, false

2.3. A Closer Look at Variables:


Variables are declared using the form.

type var_name; Where, type – data type of the variable


var_name – name of the variable

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

Example: int count = 10; char ch = ‘x’;


flaot f = 1.2F;
int a,b = 8;
Mrs. Suma M G, AP, MCA, RNSIT 9 | 45
20MCA22 Module-1
Dynamic Initialization:
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.
Value is not known at compile time but known at runtime.
Example: int port = getSocket();
double volume = 3.14 * radius * radius * height;
int itax = getTax( basic, Da, PF);
Here, volume, port, basic, Da, PF and itax is dynamically initialized at runtime.

2.4. The Scope and Lifetime of Variables:


Java allows variables to be declared within any block. A block is begin with an opening brace and ended by a
closed brace.
Scope of variable is the part of the program where the variable is accessible and determined at the compile time.
Example:
class Demo {
public static void main ( String [ ] args ) {
int x =10;
if (true) { // creates new scope
int y = 20;
System.out.println ( y ); // OK
}
System.out.println ( y ); //ERROR, not in scope
System.out.println ( x ); // OK
}
}

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
} }

Mrs. Suma M G, AP, MCA, RNSIT 10 | 45


20MCA22 Module-1
2.5. Operators:
An operators is a symbol that tells the compiler to perform a specific mathematical, logical or other
manipulations.
Table 2.3: List of operators and example
Category Operators Meaning Example

+ Addition class ArtDemo{


Subtraction public static void main(String[] args){
-
int iresult, irem;
* Multiplication
double dresult, drem;
/ Division
% Modulus iresult=10/3;
Arithmetic

++ 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

> Greater than


if(i==j)
< Less than System.out.println("Equal");
else
>= Greater than System.out.println("NotEqual");
or equal to }
<= Less than or }
equal to
& AND class RelDemo{
public static void main(String[] args){
| OR int i=10, j=11;
XOR(exclusive
Logical

^ if(i= =j)
OR)
Short-circuit System.out.println("Equal");
|| else
OR
Short-circuit System.out.println("NotEqual");
&& }
AND
}
! NOT

Mrs. Suma M G, AP, MCA, RNSIT 11 | 45


20MCA22 Module-1
Short Circuit Operator:
Provides Short-Circuit for AND & OR Logical Operators
➢ In AND (&&) – if the first operand is faJlse, the outcome is false no matter what value the second
operand has.
➢ In OR ( | | ) – if the first operand is true, the outcome is true no matter what value the second operand
has.
Example:
class ShrtCirDemo{
public static void main(String[] args){
int n=10, d=2;
if(d!=0 && (n%d) == 0) Both expressions are evaluated

System.out.println("Modulus is performed ");

d=0; Short circuit operator prevents a divisions


if(d!=0 && (n%d) == 0) by zero
System.out.println("Modulus not performed ");
if(d!=0 & (n%d) == 0) Both expressions are evaluated
System.out.println("Modulus is performed ");
}
}

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

2.6. The Assignment Operator:


It is single equal sign ( = ) that can used to assign a var = expression / value;
value to the variable.
Example: int x, y, z;
x = y = z = 100;

2.7. Shorthand Assignments:


Shorthand assignment operators that simplify the coding of certain assignment statements.

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;

Mrs. Suma M G, AP, MCA, RNSIT 12 | 45


20MCA22 Module-1

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)

Mrs. Suma M G, AP, MCA, RNSIT 13 | 45


20MCA22 Module-1
Examples:

2.8. Type conversion in Assignments:


It states that converting from one type to another type. Booleans cannot be converted to other types. There are
two types:
• Implicit Type • Explicit Type

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.

Example: int x =10; // occupies 4 bytes


double y =x; // occupies 8 bytes, Implicit coversion
System.out.println(y); // prints 10.0

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.

Syntax: (target-type)expression; Here, target-type specifies the desired type to


convert the specified expression to.
Example: double x = 10.5;
int y = (int)x; //explicit casting

The double x is explicitly converted to int y.

Mrs. Suma M G, AP, MCA, RNSIT 14 | 45


20MCA22 Module-1
2.9. Operator Precedence:
An operator’s precedence determines at what point it is evaluated in an expression. An operator with a higher
precedence will be evaluated before an operator with a lower precedence.
Table 2.4: Shows the order of precedence for all Java operators, from highest to lowest.

Highest Type Categories Precedence


Postfix expr++ expr- -
Unary (type-
Prefix ++expr --expr ~ ! + -
cast)
* / %
Arithmetic
+ -
<
Shift >> >>>
<
Comparison > >= < <= instanceof
Relational
Equality == !=
AND &
Bitwise Exclusive OR ^
Inclusive OR |
Logical AND &&
OR ||
Ternary ?:
Assignment = Op=
Lowest

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

Mrs. Suma M G, AP, MCA, RNSIT 15 | 45


20MCA22 Module-1
Chapter-3

Program Control Statements

Handling User Input / Output:


• Java I/O (Input and Output) is used to process the input and produce the output.
• uses the concept of stream to make I/O operation fast.
• The java.io package contains all the classes required for input and output operations
Stream
A stream is a sequence of data. In Java a stream is composed of bytes.
Two types of Streams:
➢ Byte Streams: handling the input and output of bytes.
➢ Character Streams: handling the input and output of characters.
Predefined Streams:
There are 3 streams variables:
1. System.in: standard input stream
2. System.out: standard output stream
3. System.err: standard error stream
By default, all these streams are the console.

3.1. Input characters from the Keyword:


➢ To read a character from the keyboard we will use System.in.read().
➢ System.in is the complement to System.out
➢ It is the input object attached to the keyboard.
➢ The read() method waits until the user presses a key and then returns the result.
➢ The character is returned as an integer, so it must be cast into a char to assign it to a char variable.
Example 3.1:
class RdChar{
public static void main(String[] args)throws IOException{
char ch;
System.out.println("enter a key");
ch=(char)System.in.read(); //Read a character
System.out.println("your key is= " +ch);
}
}

Output:

Mrs. Suma M G, AP, MCA, RNSIT 16 | 45


20MCA22 Module-1
Reading string:
String can be read using following classes

1. InputStreamReader automatically import the


2. BufferedReader
java.io package
3. Scanner java.util package

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);

Methods used for reading string in BufferedReader

Sl No. Method and description

1 int read ( ):- This method reads a single character.


int read (char[] bufArr, int off, int len)
2
- This method reads characters into a portion of an array.
3 String readLine ( ):- This method reads a line of text.
Example 3.2:
class RdBr {
public static void main(String[] args)throws java.io.IOException{
String str;
InputStreamReader ir=new InputStreamReader (System.in);
BufferedReader input = new BufferedReader(ir);
// declare in a single line.
//BufferedReader input = new BufferedReader(new
InputStreamReader(System.in));
System.out.println ("Enter a Name");
str = input.readLine();
System.out.println ("String entered is = " + str);
}
}

Mrs. Suma M G, AP, MCA, RNSIT 17 | 45


20MCA22 Module-1
3. Scanner class:
• The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default.
• It provides many methods to read and parse various primitive values.
Syntax:
Scanner sc_name= new Scanner(System.in);
sc_name.method();

Table 3.1: Methods in Scanner class

Method Returns Exception on failure


int nextInt() Returns the next token as an int. InputMismatchException
long nextLong() Returns the next token as a long.
float nextFloat() Returns the next token as a float.
double nextDouble() Returns the next token as a long.
Finds and returns the next complete token as a NoSuchElementException
String next() string; a token is usually ended by whitespace such
as a blank or line break.
Returns the rest of the current line, excluding any
String nextLine()
line separator at the end.
void close() Closes the scanner.

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();

System.out.println("Enter your name");


String name = input.next();

System.out.println("Enter your fee");


double fee = input.nextDouble();
System.out.println ("Rollno:" + rollno + " name:" + name
+ " fee:" + fee);
input.close();
}
}

Mrs. Suma M G, AP, MCA, RNSIT 18 | 45


20MCA22 Module-1
3.2 Control Statements:
Program control statements can be organized into the following categories:
1. Selection or Conditional or Decision Statements 3. Jump Statements
2. Iteration or Looping Statements

Selection or Conditional or Decision Statements:


Decision making structures have one or more conditions to be evaluated or tested, if it is true the statements get
executed and optionally, other statements to be executed if the condition is determined to be false.
Table 3.2: Types of Conditional statements

Type Syntax and Explanations Example


if(condition){ int age=20;
1. Simple if

//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("even number");


} }else{
It executes the if block if condition is System.out.println("odd number");
true otherwise else block is executed. }
if(condition1){ int age=25,basic=4000,tax = 200;
Statements;
}else if(condition2){ if (age>18) {
3. if-else-if ladder

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

Mrs. Suma M G, AP, MCA, RNSIT 19 | 45


20MCA22 Module-1
Table 3.2: Types of Conditional statements(Continued)

Type Syntax and Explanations Example

switch(expression){ int number=20;


case value1:Statements; switch(number){
break; case 10: System.out.println("10");
case value2:Statements; break;
5. switch or multiway

break; case 20: System.out.println("20");


...... break;
default: case 30: System.out.println("30");
//code to be executed break;
if all cases are not default:
matched System.out.println("Not in 10,
} 20 or 30");
The Java switch statement executes one }
statement from multiple conditions.

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

while(condition){ int i=1;


Statements; while(i<=10){
1. while

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

Mrs. Suma M G, AP, MCA, RNSIT 20 | 45


20MCA22 Module-1
Table3.3: Types of Iteration Statements (Continued)

Type Syntax and Explanations Example


for(type var : array){ int arr[]={12,23,44,56,78};
Statements;
4. Enhanced for loop

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

jump-statement; for(int i=1;i<=10;i++){


break; if(i==5){
break;
break

• used to break loop or switch statement.


}
• It breaks the current flow of the program at System.out.println(i);
specified condition. }
• In case of inner loop, it breaks only inner loop. Output: 1 2 3 4
jump-statement; for(int i=1;i<=10;i++){
continue; if(i==5){
continue;
• Used to continue loop.
continue

}
• 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 value; boolean isOdd( int num ) {


if ( num/2 == 0 )
• The return statement exits from the current
return

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.

Mrs. Suma M G, AP, MCA, RNSIT 21 | 45


20MCA22 Module-1
Table 3.4: Types of Jump Statements (Continued)

Type Syntax and Explanations Example


for( i=1 ; i<=3 ; i++){
jump-statement;
one: {
break LABEL; two: {
• The break statement can be three: {
followed by a label. System.out.println(“i=”+ i );
break label or break as a form of goto

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

continue LABEL; Outer:


for( int i = 0; i < 3; i++) {
• skips the current iteration of an for( int j = 0 ; j < 3 ; j++) {
outer loop marked with the given if( i == j)
label. continue Outer;
of goto

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+" ");
}
}

Mrs. Suma M G, AP, MCA, RNSIT 22 | 45


20MCA22 Module-1
Chapter-4

Introducing Classes, Objects and Methods

4.1 Class Fundamentals:


Syntax:
A class is a blueprint or template that
class <class_name>{
defines the variables and the methods
common to all objects of a certain kind.
//Instance variable
type var1;
• Java uses a class specification to - - - - -
construct objects. //Declare methods
• Objects are instances of a class. type method1(parameter){
//Statements
Note: A class is a logical abstraction. It is
}
not until an object of that class has been
- - - - - - - -
created that a physical representation of
that class exists in memory.
}

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);
}
}

4.2 How Objects are Created


Object is an instance of a class. Create by using keyword “new” that dynamically allocates memory for
an object and returns a reference to it.

Classname objectname = new Classname();

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()
} }}

Mrs. Suma M G, AP, MCA, RNSIT 23 | 45


20MCA22 Module-1
4.3 Reference Variables and Assignment:
Assign value of reference variable to another reference variable.
Example:
Student std1 =new Student();
Student std2=std1;
Here, std2 is initialized with std1 means – “std1 and
std2” both are referring same object, thus it does not Figure 4.1: Memory representation
create duplicate object, nor does it allocate extra memory.

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

access_specifiers ret_type name(parameter-list){


//body of method
}
Here,
access_specifiers – provide a scope using public, private, protected, default
ret_type – type of data returned by the method
name – method is specified by name
parameter-list – sequence of type and identifier pairs separated by commas
Return type of method: Method Name
➢ Method can return any Primitive data type ➢ Method name must be valid identifier.
➢ Method can return Object of Class Type ➢ All Variable naming rules are applicable for
➢ Method sometimes may not return value writing Method Name.
Parameter List
➢ Method can accept no Parameter
➢ Method can accept any number of parameters and declare it using any data type
➢ Method can accept Object as Parameter
➢ Parameters are separated by Comma.
➢ Parameter must have Data Type

4.5 Returning Value:


Returns values are used for a variety of purposes in programming.
➢ The return value contains the outcome of some calculation or simply indicate success or failure
➢ It may contain a status code
➢ Methods return a value to the calling routine

return value;

Mrs. Suma M G, AP, MCA, RNSIT 24 | 45


20MCA22 Module-1
4.6 Using Parameters:
It is possible to pass one or more values to a method when the method is invoked. A value passed to a method
is called an argument.
Inside the method, the variable that
class Rectangle {
receives the argument is called a
double lenght, breadth; parameter. Parameters are declared inside
void setLength(double len){ the parentheses that follow the method’s
length= len; name.
}
The parameter declaration syntax is the
int getLength(){
return lenght*length; same as that used for variables that shown
} in an example:
}
class RectDemo {
public static void main(String [] args){
Rectangle r1 = new Rectangle();
r1. setlength(10);
int sum = r1.getLenght();
System.out.println(“length:” +sum);
}
}

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

Mrs. Suma M G, AP, MCA, RNSIT 25 | 45


20MCA22 Module-1
Default constructor:
A constructor that have no parameter is known as default constructor. <class_name>(){
If user doesn’t supply the constructors for java class, the compiler //code
builds an implicit default constructor for that class. }

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();
}
}

4.8 The new operator Revisited:


In the context of an assignment, the “new” operator
Syntax: Class_name class_var = new Class_name();

Mrs. Suma M G, AP, MCA, RNSIT 26 | 45


20MCA22 Module-1
Here, class_var - variable of the class type being created.
Classs_name - name of the class that is being instantiated.
▪ The class name followed by a parenthesized argument list (which can be empty)specifies the constructor
for the class.
▪ The new can be used to create an object of any class type.
▪ The new operator returns a reference to the newly created object, which is assigned to class-var.

4.9 Garbage Collection and Finalizers:


An objects are dynamically allocated by using the new operator, you might be wondering how such objects are
destroyed and their memory released for later reallocation. In some languages, such as C++, dynamically
allocated objects must be manually released by use of a delete operator.
▪ Java takes a different approach; it handles deallocation automatically. The accomplished technique is
called as garbage collection.
▪ When no references to an object exist, that object is assumed to be no longer needed, and the memory
occupied by the object can be reclaimed.
▪ It is possible to define a method a finalize() that will be called just before an object’s final destruction by
the garbage collector.
Syntax: protected void finalize() throws Throwable
{
//code
}
▪ A finalize() is the opposite of a constructor and performs finalization for the object.
▪ Garbage collector can't free resources, such as open files and network connections, so need to write a
finalize() method for any object that needs to reclaimed the resources.
Example 4.3: class A{
int i = 50;
@Override
protected void finalize() throws Throwable{
System.out.println("From Finalize Method");
}
}
public class FinalizeDemo2{
public static void main(String[] args){
//Creating two instances of class A
A a1 = new A();
A a2 = new A();

a1 = a2;
System.out.println("done");

a1.finalize();
//System.gc();
}
}

Mrs. Suma M G, AP, MCA, RNSIT 27 | 45


20MCA22 Module-1
4.10 The “this” Keyword:
‘this’ is a constant reference which holds the references to the current instance of a class.
5 Uses of ‘this’ keyword
State
i. With field of instance : this.variable ; this
behaviour
ii. With constructor : this(parameter); Reference variable
iii. With method : this.method(); object
iv. as Method arguments : method(this);
v. return type in the method call : return(this);

Syntax and description Example


i.With field of instance: class ThisIV{
String pname;
this.variable ; int price;
ThisIV(String pname, int price){
The instance variable is hiding and the
this.pname = pname;
value of the local variable (or Method this.price=price;
}
Parameter) is displayed not instance void show(){
variable. System.out.println("ProductName:"+pname);
System.out.println("ProductPrice:"+price);
}
To solve this problem use this
public static void main(String[] args){
keyword. ThisIV obj=new ThisIV("Dell mouse",500);
obj.show();
}
}
ii. With constructor : class ThisCon{
String pname;
this(parameter); int price;
ThisCon(){
“this” can be used to invoke an this("Dell mouse" , 500 );
System.out.println("without parameter");
overloaded constructor in the same
}
Class.
ThisCon(String pname, int price){
this.pname = pname;
this.price = price;
System.out.println("with parameters");
show();
}
void show(){
System.out.println("ProductName"+ pname);
System.out.println("ProductPrice"+price);
}
public static void main(String[] args){
ThisCon obj=new ThisCon();
}
}

Mrs. Suma M G, AP, MCA, RNSIT 28 | 45


20MCA22 Module-1

iii.With method: class ThisMeth{


void methodOne(){
this.method(); System.out.println("Inside Method ONE");
}
“this” keyword can also be used inside
void methodTwo(){
Methods to call another Method from System.out.println("Inside Method TWO");
same Class. this.methodOne();// same as calling methodOne()
}

public static void main(String[] args) {


ThisMeth obj = new ThisMeth();
obj.methodTwo();
}
}
iv.as Method arguments: class ThisAsParam {
int i=10;
method(this);
void method() {
“this” keyword can also be passed as an method1(this);
}
argument in the method.
void method1(ThisAsParam t) {
It is mainly used in the event handling. System.out.println("I= " + t.i);
}

public static void main(String[] args) {


ThisAsParam obj = new ThisAsParam();
obj.method();
}
}

v.return type in the method call: class ThisRet


{
return(this); ThisRet getA(){
return this;
“this” keyword can be return from }
the method.
void msg(){
System.out.println("Hello java");
return type of the method must be }
the class type
public static void main(String[] args){
ThisRet obj = new ThisRet();
obj.getA().msg();
}
}

Mrs. Suma M G, AP, MCA, RNSIT 29 | 45


20MCA22 Module-1
Chapter-5

More Data Types and Operators

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

i. Single dimensional or one dimensional:


A One Dimensional Array is a list of related variables.
Declare an array:
The creation of array is two-step process
• First declare an array reference variable.
• Second allocate memory for the array using new operator.

type[] array_name;
or In Single Line, declaration and allocation
type array_name[]; type[] array_name=new type[size];

array_name = new type[size];

Here, type - declares the element type


size – indicate the number of elements that the array will hold

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

Mrs. Suma M G, AP, MCA, RNSIT 30 | 45


20MCA22 Module-1
Initialization
Arrays can be initialized when they are created.

type[] arrayName = {val1,val2,val3..valn};


Here, the initial value are specified by val1 through valN
• They are assigned in sequence, left to right, in index order.
• Java automatically allocates an array large enough to hold the initializers that you specify.
• no need to explicitly use the new operator.
Example 5.1:
class OneDim{
public static void main(String[] args){
int[] list= {10, 20, 30, 40, 50};
for(int i=0;i<5;i++)
System.out.println(i+1 + " value " + list[i]);
}
}

ii. Two dimensional or multi-dimensional:


Two dimensional or multi-dimensional arrays are array of arrays.
A two-dimensional array can be thought of as
creating a table of data, with the data organized by
row and column.
An individual item of data is accessed by specifying
its row and column position.
To declare a two-dimensional array, you must specify
the size of both dimensions.
Declare an array:
type[][] array_name;
or In Single Line, declaration and allocation
type array_name[][]; type[][]array_name=new type[row][col];

array_name=new type[row][col];

Example: int [][] table=new int[3][2];


Here, table is used to declare two dimensional array of int with 3 rows and 2 column.

Initialization
A two-dimensional array can be initialized by enclosing each dimension’s initializer list within its own set of
braces.

type[][] arrayName = {{v1,..vn},{v1,..vn},{v1,..vn}};

Mrs. Suma M G, AP, MCA, RNSIT 31 | 45


20MCA22 Module-1
Example 5.2:
class TwoDim{
public static void main(String[] args){
int[][] table=new int[][] {{10, 20},{30, 40}};

for(int i=0;i<2;i++){
for(int j=0;j<2;j++)
System.out.print(table[i][j] + " ");
System.out.println("\n");
}
}
}

iii. Irregular array or jagged array:


Java allows to set different column sizes for each
row of array is called irregular array.
To declare an irregular array, you must specify the
size in the 1st dimension and the remaining
dimensions can allocate separately as shown below.

int std[][] = new int[3][];


std[0] = new int[2];
std[1] = new int[3];
std[2] = new int[4];

Example 5.3: class IrregularDemo{


public static void main(String[] args){

int[][] table= new int[2][];


table[0]=new int[3];
table[1]=new int[1];

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");
}
}
}

Mrs. Suma M G, AP, MCA, RNSIT 32 | 45


20MCA22 Module-1
5.2 Multidimensional Arrays:
Multi-dimensional arrays are array of arrays. Allows more than 2-dimensions.
Syntax:

type[][]..[] arrayname= new type[size1][size2]..[sizeN];

Example: int[ ][][] arr=new int[2][3][4];


Initialization:
type[ ][ ] . . . [ ] array_name= { {val1, . . valN}, {val1, . . valN},
-------------
}

5.3 Assigning Array References:


As with other objects, when assign one array reference int[ ] num1= new int[5];
variable to another, you are simply changing what int[ ] num2= new int[5];
objects that variables refers to. - - - - - - - - - - - - - -
num2= num1; //assigning array references
When do “num2 = num1”, we actually assigning
reference of array. Hence if we make any change to one array, it would be reflected in other array as well
because both num1 and num2 referring the same location.

Example 5.4: class ArrRefDemo{


public static void main(String[] args){
int[] num1 = new int[]{10,20,30,40,50};
int[] num2 = new int[]{-1,-2,-3,-4,-5};
System.out.print("Here is nums1: ");
for(int i=0; i < num1.length; i++)
System.out.print(num1[i] + " ");
System.out.print("Here is nums2: ");
for(int i=0; i < num2.length; i++)
System.out.print(num2[i] + " ");
num2 = num1; //assigning references.
System.out.print("nums2 after assignment: ");
for(int i=0; i < num2.length; i++)
System.out.print(num2[i] + " ");
}
}

5.4 Using the Length Member:


Arrays are implemented as objects, each array has associated with it a length instance variable that contains
the number of elements that the array can hold. In other words, length contains the size of the array.
Example:
int[] arr=new arr[ ] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println(“Length is: ” + arr.length);
int[][]table=new table[][]{{1,2},{3,4}};
System.out.println(“row size is: ” table[0].length);

Mrs. Suma M G, AP, MCA, RNSIT 33 | 45


20MCA22 Module-1
5.5 The For-Each Style for Loop
Covered in chapter -3: Refer page no: 21

5.6 String array:


Once you have created a String object, you can use it anywhere that quoted string is allowed.
Initializing an array of strings in different ways
1. String[] str={“alpha”, “beta”, “gamma”, “teta”};
2. String[] str1;
str1=new String[5];
3. String[] str2=new String[5];
4. String[] str3= new String[] {“alpha”, “beta”, “gamma”, “teta”};
Example: String[] strs = {"This","is","a","test." };
for(String s : strs)
System.out.println(s + " ");

5.7 The Bitwise operators


Covered in chapter – 2: Refer page 31
Example 5.5: Getting uppercase for a letter
The following program demonstrates & by turning any lowercase letters into uppercase by resetting the bit to 0.
• As the UNICODE/ASCII character set is defined, the lowercase letters are the same as the uppercase
ones except that the lowercase ones are greater in value by exactly 32.
• Therefore, to transform a lowercase letter to uppercase, just turn off the 6th bit, as this program illustrates.
• The value 65,503 used in the AND statement is the decimal representation of 1111 1111 1101 1111.
Thus, the AND operation leaves all bits in ch unchanged except for the 6th one, which is set to 0.

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 + " ");
}
}
}

Mrs. Suma M G, AP, MCA, RNSIT 34 | 45


20MCA22 Module-1
Chapter-6

String Handling

6.1 String Fundamentals:


String is a class that represents sequence of characters.
• Strings are constants and their values cannot be changed after they are created, so it is called as
immutable.
• The String class is declared final, which means that can’t be sub classed
Syntax:
public final class String extends Object
implements Serializable, Comparable<String>, CharSequence
Here,
Comparable Interface – Specifies how objects are compared
CharSequence – set of methods that are applicable to a character sequence
Serializable –String can be saved and restored using java’s serialization

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:

String str1=“Hello”; String str1=“Hello”;


String str2=“Hello”; String str2=“Hi”;

str1 str1
Hello
Hello
str2 str2
Hi
Common pool Common pool

Mrs. Suma M G, AP, MCA, RNSIT 35 | 45


20MCA22 Module-1
String constructor
• JVM doesn't perform String pool check if you create object using new operator.
• Always creates new string object.
• Construct a String by using new and calling the String str1= new String();
String constructor.

Example: String s1= new String(“Welcome”);

6.2 The String Constructors:


Different form of Constructors are listed below:
Table 6.1: String Constructors

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);

5 String(char[] ch, int offset, int char[] ch={‘h’,‘e’,‘l’,‘l’, ‘o’};


length): String s=new String(b,1,3);
Constructs a new String, it represents the character sequence
from offset to length number of character.
6 String(String str): String str=“Hello”
Constructs a new String with the same sequence of characters String s=new String(s1);
as the argument.

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);

Mrs. Suma M G, AP, MCA, RNSIT 36 | 45


20MCA22 Module-1

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);
}
}

6.3 Three String-Related Language Features:


There are 3 String features:
1. String Literals:
For each string literal, automatically constructs a string object
Example: String str= “Welcome”;
2. String Concatenation:
Does not allow operations on String objects through operators except + operators, which concatenates
two strings.
Example: String s1=“Sachin”;
String s2=“Tendulkar”;
System.out.println(s1+s2);
3. String Concatenation with other data types:
You can concatenate strings with other types of data.
Example: int age=“41”;
String str=“Sachin Tendulkar is” + age + “years old”;
System.out.println(“str”);

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);
}

Mrs. Suma M G, AP, MCA, RNSIT 37 | 45


20MCA22 Module-1
6.4 The Length() Method:
Strings are not an arrays, they do not have a length field.
String does have a method called length() method, that returns the length of a string in integer type.

Syntax: int length()

Example: String s1=“Good morning”;


System.out.println(s1.length()); //12

6.5 Obtaining the characters within a string:


String class provides three ways in which character can be obtained from a string.
Table 6.2: methods for obtaining the character

Methods & Description Syntax & Example


charAt(): char charAt(int index)
returns a single character from a string at specified String str=“Java is Powerful”;
index.
char ch=str.charAt(3); //v
getChars(): obtain more than one character
void getChars(int srcstart,int srcend,char[] target,int targetStart)
Where, reads the set of characters from index srcstart to the index srcend and store in the target character
array from a given index targetStart.
String str=“Java is Powerful”;
Str.getChars(5,10,b,0);
System.out.println(b); //is pow
ToCharArray(): char[] toCharArray()
Converts this string to a new character array. String str=“Java is Powerful”;
str.ToCharArray(); //{‘j’,’a’,’v’. . .}
System.out.println(str[8]); //P

6.6 String comparison:


Different methods used for string comparison are
Table 6.3: methods for comparing the String objects

Methods & Description Syntax & Example


1. equals(): boolean equals()
It compares the string to the specified object. String str=“java”;
If the string are equal then result is true otherwise str.equals(“java”) return true;
false. str.equals(“c”) return false;

Mrs. Suma M G, AP, MCA, RNSIT 38 | 45


20MCA22 Module-1

2. equalsIgnoreCase(): boolean equalsIgnoreCase()


compares the string to the specified object without String str=“Java is Powerful”;
checking the case String str1=“java is powerful”;
str.equalsIgnoreCase(str1);
3. regionMatches():
compares specific region inside a string with another specific region in another string.
boolean regionMatches(int start, String s2, int s2index, int noch)
Where, start - specifies the index at which the region begins within the invoking String object.
s2 - The String being compared is specified by str2.
str2StartIndex - The index at which the comparison will start within str2
noch - The length of the substring being compared is passed in noCh
String str=“Java is Powerful”;
String str1=“java is powerful”;
str.regionMatches(5,str1,5,10); //true
4. startsWith()&endsWith(): boolean startsWith(String str)
Determines whether a given string begin with & end boolean endsWith(String str)
with a specified string. String str=“Java is Powerful”;
str.startsWith(“Java”); //true
str.endsWith("Java"); //false

5. compareTo(): int compareTo(String str)


Compares a String to another string Object. String str1=“Java”;
The result of the comparison is one of the following: String str2=“Java”;
• Less than zero: invoking string is less than str str1.compareTo(str2); //0
• Greater than zero: invoking string is greater
than str
• Zero: the two string are equal
6. compareToIgnoreCase(): int compareToIgnoreCase(String
Compares the string to the specified string object str)
without checking the case String str1=“Java”;
String str2=“java”;
str1.compareToIgnorecase(str2);

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

Mrs. Suma M G, AP, MCA, RNSIT 39 | 45


20MCA22 Module-1
6.7 Searching a substring using indexOf() and lastIndexOf():
Methods for searching String.
Table 6.4: Methods for searching string

Methods & Description Syntax & Example


indexOf(): • int indexOf(char ch)
• Searches for the first occurrence of the • int indexOf(String str)
specified character or substring. String str= “Java is powerful”;
• If the character or substring is not str.indexOf(‘a’); //1
within the source string, then return -1 str.indexOf(“is”); //5
• If character or substring is found, then
return the position of searchString in • int indexOf(char ch,int index)
source string • int indexOf(String str,int index)
String str= “Java is powerful”;
str.indexOf(‘a’,7); //-1

lastIndexOf(): • int lastIndexOf(char ch)


• Searches for the last occurrence of the • int indexOf(String str)
specified character or substring. String str=“Java is powerful”;
• If the character or substring is not str.lastIndexOf(‘a’); //3
within the string, then return -1
str.lastIndexOf(“is”); //5
• If character or substring is found, then
return the position of searchString in • int lastIndexOf(char ch,int index)
source string
• int lastIndexOf(String str, int
index)
String str= “Java is powerful”;
str.lastIndexOf(‘a’,7);

6.8 Changing the case of characters within a string:


The string case can change using following methods.
Table 6.5 methods for changing the case of characters
Methods & Description Syntax & Example
toLowerCase(): String toLowerCase();
Converts all of the characters in string to String str=“Java is powerful”;
lower case. str.toLowerCase(); // java is powerful
toUpperCase(): String toUpperCase();
Converts all of the characters in string to String str=“Java is powerful”;
upper case. str.toUpperCase(); // JAVA IS POWERFUL

Mrs. Suma M G, AP, MCA, RNSIT 40 | 45


20MCA22 Module-1
6.9 Obtaining a modified string:
Different methods for modifing a string.
Table 6.6: methods to modify the string

Methods & Description Syntax & Example


replace(): String replace(char oldchar, char
Returns a new string resulting from newchar)
replacing all occurrences of oldChar in String str=“Java is powerful”;
source string with newChar. str.replace('w','W'); // Java is poWerful
subString(): 1. String subString(int startindex)
Form 1. Returns a new sub string String str=“Java is powerful”;
extracted from the source string from str.substring(5); // is powerful
specified index to end. 2. String subString(int startindex,
Form 2. Returns a new sub string int endindex)
extracted from the source string from String str=“Java is powerful”;
index startindex till the index specified by
str.substring(5,7); //is
endindex
trim(): String trim();
Deletes leading and trailing whitespace String str=“ Java is powerful ”;
(spaces, tabs, newline characters) from a str.trim(); //Java is powerful
string.
concat(): String concat(String s)
Joining two string that means appending String str=“Java is powerful”;
one String to the end of another. str.concat(“Language”); //Java is powerful Language

toLowerCase(): String toLowerCase();


Converts all of the characters in string to String str=“Java is powerful”;
lower case. str.toLowerCase();

toUpperCase(): String toUpperCase();


Converts all of the characters in string to String str=“Java is powerful”;
upper case. str.toUpperCase();

6.10 StringBuffer and String Builder:


StringBuffer and StringBuilder is a mutable class; means you can change the value of the object
• At any time, the length and content of the sequence can be changed through certain method calls.
• The object created through StringBuffer and StringBulder is stored in the heap.

• StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is
synchronized.

Mrs. Suma M G, AP, MCA, RNSIT 41 | 45


20MCA22 Module-1
• Due to this it does not allow two threads to simultaneously access the same method. Each method
can be accessed by one thread at a time.
Constructor of StringBuffer class:
i. StringBuffer sb = new StringBuffer();
String buffer with no characters and an initial capacity of 16 characters.

ii. StringBuffer sb = new StringBuffer(10);


String buffer with no characters and the specified initial capacity of 10 becomes size of the buffer.

iii. StringBuffer sb = new StringBuffer(“demo”);


String buffer initialized to the contents of the specified string. So, initial capacity is 16 + content size
4: ie., 20

String Buffer can be converted to the string by using following method.

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

Mrs. Suma M G, AP, MCA, RNSIT 42 | 45


20MCA22 Module-1
Additional Examples
Example 1: Sorting the array of string
class StringSort {
public static void main( String args[] ) {
String list[] = { "Java","is", "Fun", "for", "all" };
for( int j = 0; j < list.length; j++){
for ( int i = j + 1; i < list.length; i++){
if ( list[i]. compareTo( list[j]) < 0) {
String t = list[ j ] ;
list[ j ] = list[ i ] ;
list[ i ] = t;
}
}
}
for ( int i =0; i < list.length; i++ )
System.out.println( list[i] );
}
}

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]";

int startIndex = email.indexOf("@") + 1;


int lastIndex = email.indexOf(".") ;

System.out.print("Domain Name :" );


System.out.println(email.substring(startIndex, lastIndex));
}
}

Mrs. Suma M G, AP, MCA, RNSIT 43 | 45


20MCA22 Module-1
Questions:
Sl
No. 1. Java Fundamentals
1. List and explain the features of the Java.
2. Explain the key attributes of Java programming language.
3. Describe the general structure of a simple Java Program
4. Name the Principles of OOPs. Explain
5. What is JVM? Why do we need it?
6. What is Java development kit and java runtime environment?
7. What is Keywords and Identifiers? List the rules to write an identifier.
8. Explain the following :
i. Bytecode
ii. Javac utility
iii. Java utility

2. Introducing Data types Operators


1. Discuss various data types used in Java.
2. What is type Conversion and Casting? Explain automatic type promotion in expressions with rules
and demo program.
3. Explain the term with an example:
Module -1

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.

4. Introducing Classes, Objects and Methods


1. Define class. Give its general form.
2. What are objects? How objects are created?
3. What are constructors? Explain types of constructors
4. Explain the usage of “this” keyword.
5. Explain the following:
i. finalize() ii. “this” keyword

Mrs. Suma M G, AP, MCA, RNSIT 44 | 45


20MCA22 Module-1

5. More Data Types and Operators


1. What are Arrays? Explain different types of an array.
2. How many ways an array can be initialized? Explain with a syntax.
Module -1

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.

2. Write a program to convert from lowercase to uppercase using bitwise operator.

3. Write a program to print the following pattern


A
A B
A B C
A B C D
4. Write a program to display bits within a byte(for Integer type)

5. Write a program to find minimum and maximum element of an array.

6. Write a program to searching an element of an array.

7. Write a program to sorting elements of an array.


8. Write a program to sum all elements in an array.
9. Write a program to Transpose of Matrix.
10. Write a program to sum of diagonal elements of a matrix.
11. Write a program to multiplication of two matrix.
12. Write a program to read a string from keyboard and reverse it then check whether it is
palindrome or not.
13. Write a program to read an array of string and sorting that string list.

Mrs. Suma M G, AP, MCA, RNSIT 45 | 45

You might also like