Java Unit - I
Java Unit - I
SYLLABUS
Object Oriented Programming Paradigm: Introduction to OOP Paradigm, Evolution of Java, Difference
between JDK, JRE, and JVM, Classes, Objects, Data Types, Variables, Comments, Type Conversion and
Casting, Operators, Symbolic Constants, Control Statements, Scope of Variables, Constructors, this
keyword, Overloading, Command line Arguments, Arrays, String Class, Wrapper classes.
object:
• An object is instance of class i.e., process of allocating the memory dynamically.
• Each object has an identity (reference), properties (data) And a behavior (methods).
• Syntax: Class_Name reference = new Constructor_Name ( ) ;
Abstraction
• The mechanism of showing the necessary data and hiding the unnecessary data is called abstraction.
(or)
• The process of showing the functionality and hiding the implementation details is called abstraction.
• The abstraction is achieved through abstract and interface keywords in java.
• The advantage of abstraction is readability and data hiding.
Encapsulation
• The process of grouping or wrapping or binding the properties (data) and behavior (code) into a single
unit is called encapsulation.
• Encapsulation can help to group the related properties and behaviors from raw data.
• The encapsulation is achieved by using class and package keyword.
• The advantage of encapsulation is security.
1
22PC1IT201 UNIT - I OOP Through Java
Inheritance
• Inheritance is a mechanism to obtaining the one class properties into another class.
• The inheritance is achieved by using extends and implements keywords
• Inheritance can create new class from existing class.
• The class which is giving properties is called base class (or) parent class (or) super class.
• The class which is taking properties is called derived class (or) child class (or) sub class.
• The advantage of inheritance is code reusability.
Polymorphism
• Polymorphism (Greek term, poly means many and morphs means forms) is that allows one object or
interface can exist in multiple forms.
• Polymorphism can be achieved by method overloading and method overriding concepts.
• The advantage of encapsulation is readability, and efficiency of code.
Message passing
• An object-oriented program consists of a set of objects that communicate with each other.
• Any application requires a number of objects interacting in a harmonious manner.
Composition or Aggregation
• Aggregation or composition is a relationship among classes by which a class can be made up of any
combination of objects of other classes.
• Aggregation is referred as a “part–of” or “has–a” relationship, with the ability to navigate from the whole
to its parts.
Association
• Association depicts the relationship between objects of one or more classes.
• The Degree of an association denotes the number of classes involved in a connection.
• The degree may be unary, binary, or ternary.
✓ A unary relationship connects objects of the same class.
✓ A binary relationship connects objects of two classes.
✓ A ternary relationship connects objects of three or more classes.
2
22PC1IT201 UNIT - I OOP Through Java
Evolution of Java
Release
Version Major changes
Date
JDK Beta 1995
January The Very first version was released on January 23, 1996. The principal stable
JDK 1.0
1996 variant, JDK 1.0.2, is called Java 1.
Was released on February 19, 1997. There were many additions in JDK 1.1 as
compared to version 1.0 such as
• A broad retooling of the AWT occasion show
February
JDK 1.1 • Inner classes added to the language
1997
• JavaBeans
• JDBC
• RMI
“Play area” was the codename which was given to this form and was released on
8th December 1998.
Its real expansion included: strictfp keyword
December • the Swing graphical API was coordinated into the centre classes
J2SE 1.2
1998 • Sun’s JVM was outfitted with a JIT compiler out of the blue
• Java module
• Java IDL, an IDL usage for CORBA interoperability
• Collections system
Codename- “KESTREL” Release Date- 8th May 2000 Additions:
• HotSpot JVM included
• Java Naming and Directory Interface
J2SE 1.3 May 2000
• JPDA
• JavaSound
• Synthetic proxy classes
Codename- “Merlin” Release Date- 6th February 2002 Additions:
Library improvements
• Regular expressions modelled after Perl regular expressions
• The image I/O API for reading and writing images in formats like JPEG and
February
J2SE 1.4 PNG
2002
• Integrated XML parser and XSLT processor (JAXP) (specified in JSR 5 and
JSR 63)
• Preferences API (java.util.prefs)
• Public Support and security updates for this version ended in October 2008.
Codename- “Tiger” Release Date- “30th September 2004” Originally numbered as
1.5 which is still used as its internal version.
Added several new language features such as:
September
J2SE 5.0 • for-each loop
2004
• Generics
• Autoboxing
• Var-args
Codename- “Mustang” Released Date- 11th December 2006 Packaged with a
database supervisor and encourages the utilization of scripting languages with the
JVM. Replaced the name J2SE with java SE and dropped the .0 from the version
JAVA December
number. Additions:
SE 6 2006
• Upgrade of JAXB to version 2.0: Including integration of a StAX parser.
• Support for pluggable annotations (JSR 269).
• JDBC 4.0 support (JSR 221)
Codename- “Dolphin” Release Date- 7th July 2011 Added small language changes
JAVA
July 2011 including strings in the switch. The JVM was extended with support for dynamic
SE 7
languages. Additions:
3
22PC1IT201 UNIT - I OOP Through Java
5
22PC1IT201 UNIT - I OOP Through Java
Introduction to Java
• Java team members (also known as Green Team), initiated this project to develop a language for digital
devices such as set-top boxes, televisions, etc.
• However, it was best suited for internet programming.
• Later, Java technology was incorporated by Netscape.
• Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at
Sun Microsystems, Inc. in 1991.
• This language was initially called “Oak,” but was renamed “Java” in 1995.
Simple
Java was designed to be easy for the professional programmer to learn and use effectively.
Security
Java achieved this protection by confining an applet to the Java execution environment and not allowing it
access to other parts of the computer.
Portability
Portability is a major aspect of the Internet because there are many different types of computers and
operating systems connected to it. If a Java program were to be run on virtually any computer connected to
the Internet, there needed to be some way to enable that program to execute on different systems.
Object-Oriented
Java manages to strike a balance between the purist’s “everything is an object” paradigm and the
pragmatist’s “stay out of my way” model. The object model in Java is simple and easy to extend, while
primitive types, such as integers, are kept as high-performance no objects.
Robust
Java is more robust because the java code can be executed on a variety of environments, java has a strong
memory management mechanism (garbage collector), java is a strictly typed language, it has a strong set of
exception handling mechanism, and many more.
Multithreaded
Java supports multithreaded programming, which allows you to write programs that do many things
simultaneously.
Architecture-Neutral or platform independent
Their goal was “write once; run anywhere, anytime, forever.” To a great extent, this goal was accomplished.
Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate representation called
Java bytecode. The byte code is interpreted to any machine code so that it runs on the native machine.
High performance
Java provides high performance with the help of features like JVM, interpretation, and its simplicity.
Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols. In fact,
accessing a resource using a URL is not much different from accessing a file. Java also supports Remote
Method Invocation (RMI).
Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to verify and
resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and
expedient manner. This is crucial to the robustness of the Java environment, in which small fragments of
bytecode may be dynamically updated on a running system.
6
22PC1IT201 UNIT - I OOP Through Java
7
22PC1IT201 UNIT - I OOP Through Java
object:
• An object is instance of class i.e., process of allocating the memory dynamically.
• Each object has an identity (reference), a properties (data) And a behavior (methods).
• Syntax: Class_Name reference = new Constructor_Name ( ) ;
method:
• A method is set of statements that designed to perform a specific task.
• Every method must be part of some class.
Syntax:
<access_modifier> <return_type> <method_name> ( list_of_parameters)
{
//body
}
• Modifier: It defines the access type of the method i.e., from where it can be accessed in your
application. It is Optional in syntax.
• return type: The data type of the value returned by the method or void if does not return a value.
It is Mandatory in syntax.
• Method Name: name of the method must follow the identifier rules. It is Mandatory in syntax.
8
22PC1IT201 UNIT - I OOP Through Java
• Parameter list: Comma-separated list of the input parameters is defined, preceded by their data
type, within the enclosed parenthesis. If there are no parameters, must use empty parentheses ( ). It
is Optional in syntax.
• Method body: it is enclosed between braces. The code you need to be executed to perform your
intended operations.
Advantage of Method
• Code Reusability
• Code Optimization
Output:
Volume is 3000 cm
9
22PC1IT201 UNIT - I OOP Through Java
Data Types
• It is a mechanism to specify the kind of data stored in variable.
• Data type help to specify type of data, memory required for variable and default values.
2. Floating-Point Types:
• There are two kinds of floating-point types, float and double, which represent single- and double-
precision numbers, respectively.
• Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision.
• For example, calculations such as square root, or transcendental such as sine and cosine, result in a
value whose precision requires a floating-point type.
• The default value for float is 0.0f and for double 0.0d.
10
22PC1IT201 UNIT - I OOP Through Java
3. Characters
• The data type used to store characters is char.
• Java uses Unicode to represent characters.
• Unicode defines a fully international character set that can represent all of the characters found in all
human languages.
• In Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars.
• The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the
extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255.
• The default value is ‘\u0000’.
4. Booleans
• Java has a primitive type, called Boolean, for logical values. It can have only one of two possible
values, true or false. The default value is false.
Example: Demonstrate the various primitive data types
class DataTypeDemo{
public static void main(String[] args){
int myNum = 5; // Integer
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
System.out.println("Integer :"+myNum);
System.out.println("Floating point number :"+myFloatNum);
System.out.println("Character :"+myLetter);
System.out.println("Boolean :"+myBool);
System.out.println("String :"+myText);
}
}
Output:
Integer :5
Floating point number :5.99
Character :D
Boolean :true
String :Hello
Variables:
• A variable is name given to the particular memory location and it having a value.
• A variable is defined by the combination of data type, an identifier, and an optional initializer.
• Declaration: process of allocating the memory. number
• Syntax datatype identifier;
• Example int number;
1234
• Initialization: process of allocating value. Equal to (=) operator is used to initialize the value.
• Compile time Initialization: Allocation of value at the time of declaration.
• Syntax datatype identifier = value ;
• Example int number = 10 ;
• Run time Initialization: Allocation of value at the time of execution.
• Syntax datatype identifier;
number
identifier = 10;
• Example datatype number = 10 ; 10
number = 10;
1234
• Here, datatype is one of Java’s atomic types.
identifier is the name of the variable.
initialize the variable by specifying an equal sign and a value and the expression must result in a value
of the same (or compatible).
• The value with in the variable can be accessed by its name.
• Note: A variable can store single value at a time. If new value is arriving then previous value will be
erased.
1) Local Variable
• A variable declared inside the body of the method is called local variable.
• You can use this variable only within that method and the other methods in the class aren't even aware
that the variable exists.
• A local variable cannot be defined with "static" keyword.
2) Instance Variable
• A variable declared inside the class but outside the body of the method, is called an instance variable.
• You can use this variable only within that class.
• It is not declared as static.
• It is called an instance variable because its value is instance-specific.
3) Static variable
• A variable that is declared as static is called a static variable.
• It cannot be local.
• You can create a single copy of the static variable and share it among all the instances of the class.
• Memory allocation for static variables happens only once when the class is loaded in the memory.
12
22PC1IT201 UNIT - I OOP Through Java
Comments
• The Java comments are the statements in a program provide description about code or statement.
• Comments are not executed by the compiler and interpreter.
• Comments are help to improve readability and find the errors easily.
• There are three types of comments in Java.
1) Single Line Comment
• The single-line comment is used to comment only one line of the code.
• Single line comments start with two forward slashes (//).
• Syntax: //This is single line comment
13
22PC1IT201 UNIT - I OOP Through Java
Operators:
• An operator is symbols used for performing specific operations in Java.
• Every operator having two properties.
• Precedence:
➢ Precedence refers to the priority given to the operator for a process.
➢ An expression contained many operators, the operations carried out based on priority of operator.
➢ The highest priority operations are solved first.
• Associativity:
➢ Associativity means the direction of executing an operation.
➢ Associativity are two types
left to right: - The expression evaluation starts from left to right direction.
Ex:- 12 * 4 + 7
= 48 + 7 =55
right to left :- The expression evaluation starts from right to left direction.
Ex: x = 8 + 5
x = 13
• Types of Operators:
1. Arithmetic Operators: The basic arithmetic operations—addition, subtraction, multiplication, and division—all
behave as you would expect for all numeric types.
Operator Use
* Multiplication
/ Division
% Modulo
+ Addition
– Subtraction
Example:
class ArithmeticOperators {
public static void main (String[] args) {
int a = 10;
int b = 3;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}
Output
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1
15
22PC1IT201 UNIT - I OOP Through Java
2. Unary Operators: Unary operators need only one operand. They are used to increment,
decrement, or negate a value.
Operator Result
– Unary minus
+ Unary plus
++ Increment operator
–– Decrement operator
! Logical not operator
Example:
class UnaryOperators {
public static void main(String[] args)
{
int a = 10;
int b = 10;
System.out.println("Postincrement : " + (a++));
System.out.println("Preincrement : " + (++a));
System.out.println("Postdecrement : " + (b--));
System.out.println("Predecrement : " + (--b));
}
}
Output:
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
3. Assignment Operator: ‘=’ Assignment operator is used to assign a value to any variable.
• The assignment operator can be combined with other operators to build a shorter version of the
statement called a Compound Statement.
• For example, instead of a = a+5, we can write a += 5.
• Compound operators are +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=.
Example:
class AssignmentOperator {
public static void main(String[] args)
{
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6
5. Logical Operators: These operators are used to perform “logical AND” and “logical OR”
operations, i.e., a function similar to AND gate and OR gate in digital electronics.
Conditional operators are && (Logical AND), || (Logical OR), ! (Logical NOT).
Example:
class GFG {
public static void main (String[] args) {
boolean x = true;
boolean y = false;
System.out.println("x && y: " + (x && y));
17
22PC1IT201 UNIT - I OOP Through Java
6. Ternary Operator
The ternary operator is a shorthand version of the if-else statement.
It has three operands and hence the name Ternary.
Syntax: condition ? true : false ;
The above statement means that if the condition evaluates to true, then execute the statements after
the ‘?’ else execute the statements after the ‘:’.
7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a number. They can be
used with any of the integer types.
Operator Result
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
8. Shift Operators
These operators are used to shift the bits of a number left or right.
Operator Result
<< Left shift operator
>> Signed Right shift operator
>>> Unsigned Right shift operator
9. instance of operator
It can be used to test if an object is an instance of a class, a subclass, or an interface.
Syntax: object instance of class/subclass/interface
Symbolic Constants
• symbolic constant is a named constant value defined once and used in program.
• Symbolic constants are declared using the final keyword.
• symbolic constant value cannot be changed once it is initialized.
• You can initialize a final variable when it is declared or in constructor only.
• If your class having multiple constructors then it must be initialized in all constructor.
• A final variable that is not initialized during declaration is called blank final.
• A blank final static variable can be initialized inside a static block.
• If the final variable is a reference, then the variable cannot reference another object, but the internal state
of the object pointed by that reference variable can be changed.
• Syntax: final data_type CONSTANT_NAME = value;
• Example: final double PI = 3.14159;
19
22PC1IT201 UNIT - I OOP Through Java
Control Statements
• Control statements are used to manage the flow of execution of a program.
• They allow users to:
✓ Make decisions
✓ Repeat actions
✓ Jump from one section to a different section
• Control statements are three types.
1. Conditional Statements
2. Looping/Iteration Statements
3. Unconditional /Jump Statements
1. Conditional Statements:
• Conditional statements are used to manage the flow of execution based on condition/decision.
• They allow a programmer to specify conditions that determine which statements are executed and
which are skipped.
• The conditional statements are as follows
a) If statement
It will go inside the block only if the condition is true otherwise, it will not execute the block.
Syntax if(condition) {
// statements
}
b) If-else statement
If the condition is true then, it will execute the If block. Otherwise, it will execute the Else block.
Syntax if(condition){
// statements
}
else{
// statements
}
c) If-else-if statement
If the condition is true, then it will execute the If block. Otherwise, it will execute the Else-If block.
Again, if the condition is not met, then it will move to the else block.
Syntax if(condition){
// statements
}
else if{
// statements
}
else{
//statements
}
20
22PC1IT201 UNIT - I OOP Through Java
d) Switch statement
Switch statement allows program to select one action among multiple actions during the program
execution.
Syntax: switch(variable/value/expression) {
case value1:
// statements [];
break;
case value2:
// statements [];
break;
…
default: // statements [];
}
2. Looping/Iteration Statements
a) for loop
• It executes the code until condition is false.
• It is used when number of iterations are known.
• for is called entry-controlled loop.
Syntax:
for(initialization; condition; increment/decrement){
//statements
}
b) while loop
• It repeats a statement or block while its controlling expression is true.
• while loop is called entry-controlled loop.
Syntax:
while(condition){
// statements
}
c) do-while loop
• In do-while loop, it will execute the loop first, then it checks the condition. So, it will execute the
loop at least once.
• It is called exit controlled loop
Syntax:
do{
// statements
}while(condition);
21
22PC1IT201 UNIT - I OOP Through Java
Scope of Variables
• The visibility or accessibility of a variable is called scope of variable.
• In programming, a variable can be declared and defined inside a class, method, or block.
• We can declare variables anywhere in the program but it has limited scope.
Example:
public class ScopeDemo
{
int x =10;
{
int y = 30;
}
public void add(){
int z = x+y;
System.out.println("Addition is :"+z);
}
public static void main(String args[])
{
ScopeDemo sd = new ScopeDemo();
sd.add();
}
}
Output:
22
22PC1IT201 UNIT - I OOP Through Java
Constructor:
• Constructor is a special method which is used to initialize the object or initialize the instance
variables.
• Syntax: access ClassName( )
{
Body;
}
• Characteristics:
➢ Class name and constructor name must be same.
➢ Constructor does not have return type; therefore, it cannot return a value.
➢ Constructors are executed or invoked automatically when the objects are created.
➢ Constructor should be declared in the public section.
➢ They cannot be inherited, through a derived class can call the base class constructor.
➢ Constructor cannot be virtual.
Types of constructors:
1. Default constructor: A constructor which is created automatically by the compiler is called default
constructor.
2. Parameter-less constructor: A constructor that cannot take parameters is called parameter less
constructor.
3. Parameterized constructor: The constructor that can take the parameters is called parameterized
constructors. Parameterized constructor is used to initialize the data members dynamically.
Example: Demonstrating the constructor
class Student { //class declaration
int rollno;
String name;
String dept;
public Student( ){ //parameter-less constructor
rollno = 5;
name = "Apple";
dept = "IoT";
}
public Student(int rollno, String name, String dept){ //parameterized constructor
this.rollno = rollno;
this.name = name;
this.dept = dept;
}
public void studentDetails( ){ //method definition
System.out.println("Student Roll no:"+rollno);
System.out.println("Student Name:"+name);
System.out.println("Student Department:"+dept);
}
}
class SttudentDemo {
public static void main(String[] args) {
Student st1 = new Student( ); //object creation
st1.studentDetails( );
Student st2 = new Student(10,"Mango","CSE"); //object creation
st2.studentDetails( );
}
}
23
22PC1IT201 UNIT - I OOP Through Java
this keyword
• this is a reference variable that refers to the current object.
• this keyword can also be used –
✓ to invoke current class constructor.
✓ to resolve the ambiguity between instance variable and local variable.
✓ to invoke current class method (implicitly).
✓ to refer the current class object.
✓ passed as an argument in the method call.
✓ passed as argument in the constructor call.
✓ to return the current class instance from the method.
24
22PC1IT201 UNIT - I OOP Through Java
Method Overloading
• A class contain Two or more methods having same method name and but different in number of
parameters and/or type of parameters is called method overloading.
• Method overloading in Java is also known as Compile-time Polymorphism, Static binding, or Early
binding.
• Advantage: Method overloading increases the readability of the program.
Different ways to overload the method
Output:
Area of Triangle : 10.72
Area of Circle : 128.614
Area of Trapezoidal :18.25
25
22PC1IT201 UNIT - I OOP Through Java
Constructor Overloading
• A class contain Two or more constructors and but different in number of parameters and/or type of
parameters is called constructor overloading.
• The constructor would initialize different instance variable depending upon the argument list in the
constructor call.
class Student {
int rollno;
String name;
String dept;
public Student( ){
rollno = 5;
name = "Apple";
dept = "IoT";
}
public Student(int rollno, String name, String dept){
this.rollno = rollno;
this.name = name;
this.dept = dept;
}
public void studentDetails( ){
System.out.println("Student Roll no:"+rollno);
System.out.println("Student Name:"+name);
System.out.println("Student Department:"+dept);
}
}
class SttudentDemo {
public static void main(String[] arg) {
Student st1 = new Student( );
st1.studentDetails();
}
Output:
Student Roll no:5
Student Name:Apple
Student Department:IoT
Student Roll no:10
Student Name:Mango
Student Department:CSE
26
22PC1IT201 UNIT - I OOP Through Java
Limitations:
• We can overload constructor, main, final and static methods
• We cannot overload methods that differ only return type.
27
22PC1IT201 UNIT - I OOP Through Java
Arrays
• An array is an object which contains of group of like-typed variables that are stored in contiguous
memory and referred to by a common name.
• we can find length of array using the object property length.
• The variables in the array are ordered, and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method parameter.
• The size of an array must be specified by int or short value and not long.
• In Java, all arrays are dynamically allocated.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and Serializable
• This storage of arrays helps us randomly access the elements of an array.
• The size of the array cannot be altered (once initialized). However, an array reference can be made to
point to another array.
• The elements in the array allocated by new will automatically be initialized to zero (for numeric
types), false (for boolean), or null (for reference types).
• Advantages are code Optimization and Random access.
• Disadvantage is Size Limit
• Types of Arrays in java
1. Single Dimensional Array
2. Two Dimensional Array
1. Single Dimensional Array: group of elements having the same data type which are stored in a linear
arrangement (row or column) under a single variable name.
Declaration: allocation of memory for array reference variable.
Syntax: dataType arr[ ]; (or) dataType[ ] arr; (or) dataType [ ]arr;
Example: int marks[ ]; (or) int[ ] marks; (or) int [ ]marks;
Instantiation: allocation of memory for array object.
Syntax: arrayRefVar = new datatype[size];
Example: marks = new int [6];
Combination of both declaration and instantiation
dataType arr[ ] = new datatype[size];
int marks[ ] = new int [6];
Initialization: Assigning a value to an array.
Compile time initialization: int marks[ ] = {50,80,60,87,90,75}; (or)
int marks[ ] = new int[ ]{50,80,60,87,90,75};
Run time initialization: marks[0] = 50;
marks[1] = 80;
Accessing: Access the elements in an array by using index.
Example: marks[0]; // It access the element 50.
28
22PC1IT201 UNIT - I OOP Through Java
System.out.print(table[i][j]+" ");
}
System.out.println();
}
}
}
Output:
1 2
3 4
Jagged Array
• A jagged array in Java is a collection of arrays where each array may contain a varied number of
elements. A two-dimensional array, in contrast, requires all rows and columns to have the same length.
• Declaration and Initialization of Jagged array:
Syntax:
data_type array_name[][] = new data_type[n][]; //n: no. of rows
array_name[] = new data_type[n1] //n1= no. of columns in row-1
array_name[] = new data_type[n2] //n2= no. of columns in row-2
array_name[] = new data_type[n3] //n3= no. of columns in row-3
.
.
.
array_name[] = new data_type[nk] //nk=no. of columns in row-n
30
22PC1IT201 UNIT - I OOP Through Java
Example:
public class JaggedArraysDemo {
public static void main(String[] args) {
int table[][] = new int[5][];
table[0] ={1};
table[1] = {1,2};
table[2] ={1,2,3};
table[3] = {1,2,3,4};
table[4] = {1,2,3,4,5};
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();
}
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
31
22PC1IT201 UNIT - I OOP Through Java
String Class
• string is an object that represents sequence of char values.
• The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
public final class String extends Object
implements Serializable, Comparable<String>, CharSequence {
//body
}
• There are two ways to create String object:
1. By string literal: String literal is created by using double quotes.
Example: String s="welcome";
2. By new keyword
Example: String s=new String("Welcome");
Constructors:
Constructor Description
Initializes a newly created String object so that it represents an
String( )
empty character sequence.
Constructs a new String by decoding the specified array of bytes
String(byte[] bytes)
using the platform's default charset.
Constructs a new String by decoding the specified array of bytes
String(byte[] bytes, Charset charset)
using the specified charset.
Deprecated.
This method does not properly convert bytes into characters. As
String(byte[] ascii, int hibyte) of JDK 1.1, the preferred way to do this is via
the String constructors that take a Charset, charset name, or that
use the platform's default charset.
Constructs a new String by decoding the specified subarray of
String(byte[] bytes, int offset, int length)
bytes using the platform's default charset.
String(byte[] bytes, int offset, Constructs a new String by decoding the specified subarray of
int length, Charset charset) bytes using the specified charset.
Deprecated.
This method does not properly convert bytes into characters. As
String(byte[] ascii, int hibyte, int offset,
of JDK 1.1, the preferred way to do this is via
int count)
the String constructors that take a Charset, charset name, or that
use the platform's default charset.
String(byte[] bytes, int offset, Constructs a new String by decoding the specified subarray of
int length, String charsetName) bytes using the specified charset.
Constructs a new String by decoding the specified array of bytes
String(byte[] bytes, String charsetName)
using the specified charset.
Allocates a new String so that it represents the sequence of
String(char[] value)
characters currently contained in the character array argument.
Allocates a new String that contains characters from a subarray
String(char[] value, int offset, int count)
of the character array argument.
String(int[] codePoints, int offset, Allocates a new String that contains characters from a subarray
int count) of the Unicode code point array argument.
Initializes a newly created String object so that it represents the
String(String original) same sequence of characters as the argument; in other words, the
newly created string is a copy of the argument string.
Allocates a new string that contains the sequence of characters
String(StringBuffer buffer)
currently contained in the string buffer argument.
Allocates a new string that contains the sequence of characters
String(StringBuilder builder)
currently contained in the string builder argument.
32
22PC1IT201 UNIT - I OOP Through Java
Methods:
S.No. Method Description
1 char charAt(int index) It returns char value for the particular index
2 int length() It returns string length
static String format(String format,
3 It returns a formatted string.
Object... args)
static String format(Locale l, String
4 It returns formatted string with given locale.
format, Object... args)
5 String substring(int beginIndex) It returns substring for given begin index.
String substring(int beginIndex, int
6 It returns substring for given begin index and end index.
endIndex)
It returns true or false after matching the sequence of char
7 boolean contains (CharSequence s)
value.
static String join(CharSequence
8 It returns a joined string.
delimiter, CharSequence... elements)
static String join(CharSequence
9 delimiter, Iterable<? extends It returns a joined string.
CharSequence> elements)
10 boolean equals(Object another) It checks the equality of string with the given object.
11 boolean isEmpty() It checks if string is empty.
12 String concat(String str) It concatenates the specified string.
13 String replace(char old, char new) It replaces all occurrences of the specified char value.
String replace(CharSequence old,
14 It replaces all occurrences of the specified CharSequence.
CharSequence new)
static String equalsIgnoreCase(String
15 It compares another string. It doesn't check case.
another)
16 String[ ] split(String regex) It returns a split string matching regex.
17 String[ ] split(String regex, int limit) It returns a split string matching regex and limit.
18 String intern() It returns an interned string.
19 int indexOf(int ch) It returns the specified char value index.
It returns the specified char value index starting with given
20 int indexOf(int ch, int fromIndex)
index.
21 int indexOf(String substring) It returns the specified substring index.
int indexOf(String substring, int It returns the specified substring index starting with given
22
fromIndex) index.
23 String toLowerCase() It returns a string in lowercase.
24 String toLowerCase(Locale l) It returns a string in lowercase using specified locale.
25 String toUpperCase() It returns a string in uppercase.
26 String toUpperCase(Locale l) It returns a string in uppercase using specified locale.
27 String trim() It removes beginning and ending spaces of this string.
28 static String valueOf(int value) It converts given type into string. It is an overloaded method.
33
22PC1IT201 UNIT - I OOP Through Java
Wrapper classes
• Wrapper classes provide a way to use primitive data types (int, boolean, etc.) as objects.
• The table below shows the primitive type and the equivalent wrapper class:
Primitive Data Type Wrapper Class Primitive Data Type Wrapper Class
byte Byte float Float
short Short double Double
int Integer boolean Boolean
long Long char Character
• Wrapper classes also provide methods for converting primitive data types to objects and vice versa.
• For example, the following code converts the int value 10 to a Integer object:
Integer myInteger = Integer.valueOf(10);
Advantages:
✓ Collections allowed only object data.
✓ On object data we can call multiple methods compareTo(), equals(), toString()
✓ Cloning process only objects
✓ Object data allowed null values.
✓ Serialization can allow only object data.
Disadvantages:
✓ They can add overhead to your code.
✓ They can make your code more complex.
✓ They can be difficult to use in some cases.
Example: Demonstrate a type wrapper.
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100);
int i = iOb.intValue(); System.out.println(“Value :”+ iOb);
}
}
Output: Value :100
Autoboxing and Unboxing
1. Autoboxing
• The automatic conversion of primitive types to the object of their corresponding wrapper classes is
known as autoboxing.
• There is no need to explicitly construct an object
2. Unboxing
• It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to
its corresponding primitive type is known as unboxing.
• There is no need to call a method such as intValue( ) or doubleValue( ).
Example: Demonstrate the autoboxing and unboxing
public class AutoBoxingDemo{
static int m(Integer v) {
return v ; // auto-unbox to int
}
public static void main(String args[]) {
Integer iOb = m(100); // autobox to Integer
System.out.println("Value :"+iOb);
}
}
34
22PC1IT201 UNIT - I OOP Through Java
Model Questions
2 marks questions
1. List and define principles of OOP’s.
2. List the features of java.
3. What is platform independent?
4. What is class and write its syntax.
5. What is object and write its syntax.
6. What is the use of new keyword
7. Define constructor and write its syntax.
8. Write the characteristics of constructor.
9. Differentiate JDK, JVM and JRE.
10. Write the difference between primitive and non-primitive.
11. Define variable and write its syntax.
12. What is scope of variable?
13. Differentiate between local and instance variables?
14. Differentiate between static and instance variables?
15. Differentiate type conversion and type casting.
16. What is command line arguments?
17. Write the uses of this keyword.
18. Write a short note on symbolic constants.
19. What is jagged array and write its syntax.
20. What is wrapper class and write its use.
Essay questions
1. Explain object-oriented programming concepts in details.
2. List the features of JAVA and explain briefly.
3. What is the use of constructor? Explain characteristics and types of constructors with example.
4. Define and explain about method overloading with an example.
5. Define and explain about constructor overloading with an example.
6. List and explain different primitive data types in java.
7. What is variable? Explain about different types of variables with example.
8. Does Java support multi way selection statement? Justify your answer.
9. Define Array. Explain declaration, initialization and accessing of 1-Dimentianal array with example.
10. What is string? List and explain constructors and methods of String class with simple example.
11. Write a short note on various control statements in java.
35