Java Unit 1 Notes
Java Unit 1 Notes
UNIT-1
Introduction: Basics of object-oriented programming, comparison of procedure-oriented and object
oriented programming paradigms; Difference between C and Java Programming languages; Features of
Java; Objects and classes in Java, Structure of a Java program; Data Types, variables and operators in java;
Control structures- Branching and looping; Methods & Constructors in java; Java Development Kit (JDK);
Built-in classes in Java; Math, Character, String, String Buffer and Scanner; Wrapper classes; The abstract,
static and final classes; Casting objects; The instance of operator; Usage of this keyword; Arrays in Java.
History of java
JAVA BASICS
Java is a general purpose, object oriented programming language developed by Sun MicroSystems in
1991. Originally called OAK by James gosling , Father of java programming language. But was renamed as
java in 1995
Below is the Java applications list:
}
Objec
t object is a real world entity.
An
An object is an instance of a class.
Storage Classes Supported ( auto, extern ) Supported ( auto, extern ) Not supported
1. Java PROGRAM STRUCTURE:
A java program may contain many classes of which only one class defines a main
method. Classes contain datamembers and methods that operate on the data members of
the class.
Output:
Hello, World
[Link] definition:This line uses the keyword class to declare that a new class is being [Link]
HelloWorld HelloWorld is an identifier that is the name of the class. The entire class definition,
including all of its members, will be between the opening curly brace { and the closing curly
brace } .
[Link] method: In Java programming language, every application must contain a main method
whose signature is:public static void main(String[] args) public: So that JVM can execute the method
from anywhere. static: Main method is to be called without object. The modifiers public and static
can be written in either order. void: The main method doesn't return anything. main(): Name
configured in the JVM. String[]: The main method accepts a single argument: an array of elements of
type [Link] in C/C++, main method is the entry point for your application and will subsequently
invoke all the other methods required by your program.
[Link] next line of code is shown here. Notice that it occurs inside main( ).[Link]("Hello,
World"); This line outputs the string “Hello, World” followed by a new line on the screen. Output is
actually accomplished by the built-in println( ) method. System is a predefined class that provides
access to the system, and outis the variable of type output stream that is connected to the console.
[Link]: They can either be multi-line or single line comments./* This is a simple Java program.
Call this file "[Link]". */ This is a multiline comment. This type of comment must begin with
/* and end with */. For single line you may directly use // as in C/C++.
[Link] a java program:
Implementation of java application program involves a series of steps. They include
•Creating the program
•Compiling the program
•Running the program
Remember that, before we begin creating the program, JDK must be properly installed on our system.
Creating the program:
We can create a program using any text editor
class Sample
{
public static void main(String arg[])
{
[Link](“Hi friend”);
}
}
We have to save this program with a name like [Link]
A java Application have any no of classes, but only one main class. Main class is nothing but class which
contains main() method
Compiling the program:
To compile the program we must run the java compiler javac, with the name of the source file on command line as
shown below
C:\> javac [Link]
If everything is OK, java compiler(javac) creates a file called [Link] (<[Link]>) containing the
bytecodes of the program [Link]
Running the program:
We need to use the java interpreter to run stand alone applications. At the command prompt, type…
C:\> java Sample
Now, the interpreter looks for the main method in the program and begins execution from there. When executed
our program displays the following
o/p: Hi friend
[Link] Virtual Machine:
Generally all language compilers translate source code into machine code for a specific computer. In java,
architectural neutral is achieved because compiler produces an intermediate code called Byte code, for a
machine is called JVM
When we compile a .java file, .classfiles(contains byte-code) with the same class names present in .java file
are generated by the Java compiler. This .class file goes into various steps when we run it. These steps
together describe the whole JVM.
Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the classloader
Class Loader: The class loader reads the .class file and save the byte code in the method area.
Method area :In method area, all class level information like class name, immediate parent class
name, methods and variables information etc. are stored, including static variables. There is only
one method area per JVM.
Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for
each .class file.
Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary
variables.
PC Registers: This keeps the track of which instruction has been executed and which one is going
to be executed.
• String string2 = new String("This is a Java class "); //declaring string using new
operator
• [Link](string1);
• [Link](string2);
• }
• }
• Output:
• Hello World
This is a Java Tutorial
• Arrays: Java array is an object which contains elements of a similar
data type. Arrays store one or more values of a specific data type and
provide indexed access to store the same.
The valid syntax for array The valid syntax for array initialization can be:
declaration can be: array_name = new data-type [size of array];
data-type array_name [ ]; array_name = new data-type {elements of array using
data-type [ ] array_name; using commas};
public class Arraydemo
{
public static void main(String args[])
{
int [ ] marksOfStudents = new int[ ] {65, 90, 78, 60, 84 };
[Link]("Marks of first student: " +marksOfStudents[0]);
[Link]("Marks of second student: "
+marksOfStudents[1]);
[Link]("Marks of third student: " +marksOfStudents[2]);
[Link]("Marks of fourth student: " +marksOfStudents[3]);
[Link]("Marks of fifth student: " +marksOfStudents[4]);
}
}
• Marks of first student: 65
Marks of second student: 90
Marks of third student: 78
Marks of fourth student: 60
Marks of fifth student: 84
• Classes: A class is a collection of objects of the same type. It is a
user-defined blueprint or prototype which defines the behavior or
state of objects. A class contains fields(variables) and methods to
describe the behavior of an object.
• We create a class using a class keyword.
• A class can be declared using the following components in the order-
• 1. Access modifiers: Access modifiers define the access privileges of a
class. A class can be public or it has default access.
• 2. Class name: The name of a class should represent a noun and must
start with a capital letter. These are the best practices to be kept in
mind while declaring any class.
• 3. Body: The class body contains properties and methods. The body is
always enclosed by curly braces { }.
Syntax of writing a class:
AccessModifier class class_name
{
Class body - variables and methods();
}
}
Output:
Marks of student: 76
• An interface behaves like a blueprint of a class,
which specifies “what a class has to do and not how
it will do”.
• Interface: Like a class, an interface can have
methods and variables, but the methods
declared in interface are by default abstract (only
method signature, no body).
A variable is a name given to a memory location. It is the basic unit of storage in a program.
•The value stored in a variable can be changed during program execution.
•A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
•In Java, all the variables must be declared before use.
How to declare variables?
We can declare variables in java as follows:
Types of variables
There are three types of variables in Java:
Local Variables
Instance Variables
Static Variables
Let us now learn about each one of these variables in detail.
Local Variables: A variable defined within a block or method or constructor is called local variable.
These variable are created when the block in entered or the function is called and destroyed after exiting from
the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is declared. i.e. we can access
these variable only within that block.
Initilisation of Local Variable is Mandatory.
public class StudentDetails {
public void StudentAge()
{
// local variable age
int age = 0;
age = age + 5;
[Link]("Student age is : " + age);
}
class MarksDemo {
public static void main(String args[])
{
// first object
Marks obj1 = new Marks();
[Link] = 50;
[Link] = 80;
[Link] = 90;
// second object Output:
Marks obj2 = new Marks(); Marks for first object:
[Link] = 80; 50
[Link] = 60; 80
[Link] = 85; 90
Marks for second
object: 80
// displaying marks for first object 60
[Link]("Marks for first object:"); 85
[Link]([Link]);
[Link]([Link]); As you can see in the above program the
[Link]([Link]); variables, engMarks , mathsMarks , phyMa
rksare instance variables. In case we have
// displaying marks for second object multiple objects as in the above program,
[Link]("Marks for second object:");each object will have its own copies of
[Link]([Link]); instance variables. It is clear from the
[Link]([Link]); above output that each object will have its
[Link]([Link]); own copy of instance variable.
s.o.p(engmarks);
}
}
•Static Variables: Static variables are also known as Class [Link] variables are declared similarly
as instance variables, the difference is that static variables are declared using the static keyword within a
class outside any method constructor or block.
•Unlike instance variables, we can only have one copy of a static variable per class irrespective of how
many objects we create.
•Static variables are created at the start of program execution and destroyed automatically when execution
ends.
•If we access the static variable like Instance variable (through an object), the compiler will show the
warning message and it won’t halt the program. The compiler will replace the object name to class name
automatically.
•If we access the static variable without the class name, Compiler will automatically append the class name.
To access static variables, we can simply access the variable as. .
class_name.variable_name;
import [Link].*;
class Emp {
•Each object will have its own copy of instance variable whereas We can only have one copy of a static
variable per class irrespective of how many objects we create.
•Changes made in an instance variable using one object will not be reflected in other objects as each object
has its own copy of instance variable. In case of static, changes will be reflected in other objects as static
variables are common to all object of a class.
•We can access instance variables through object references and Static Variables can be accessed directly
using class name.
We can define the symbolic constant in Java, by using keyword final. This is similar to keyword const in c
and c++.
The keyword final proceeds the data type of a variable. It specifies that the value of a variable will not
change throughout the program . Any attempt to alter the value of a variable defined with this qualifier
will cause an error from the compiler. The syntax is
A streams required to accept input from the keyboard. A stream represents flow of data from
one place to another place. A stream can carry a data from keyboard to memory or from memory
to monitor or from memory to printer. There are two types of stream, input and output streams.
Input stream are those streams which recieve or read data from some other place. Output
streams are those streams which send or write data to some other place.
The console is represented by a field called out in System class. similarly the keyboard is
represented by a field called in in System class . We can read javas input from [Link]
console and write output to console using “[Link]”. There are two common ways to read
input from
Step2: Connect InputTreamReader to BufferedReader Which is another input stream. We are using
BufferedReader as it has got methods to read data properly from the input stream.
Step3: now, we can read the data from the keyboard using read() an readLine() methods of BufferedReader
class.
Step4: to read entire line from Keyboard use the below code. The entire text entered in the keyboard is
assigned to String object str.
String str=[Link]();
Step5: to read integer from keyboard.
Int age= [Link]([Link]());
Remember that what ever we enter in the console is treated as string and hence we should convert it
to our required data tyoe. The cod [Link]() returns the string and converting this string to an
jnteger, we should use above code .
Output : enter your name
Import [Link].*; ABC
Public class Read Enter your age
{ 6
public static void main(String args[]) Are you male / female type M or F
{ F
BufferedReader b= new BufferedReader(new InputStreamReader([Link])); Name is ABC
[Link](“enter your name:”); // to read entire line Age is 6
String str=[Link](); Gnder is F
[Link](“enter your age:”); // to read integer
int age= [Link]([Link]());
[Link](“ are you male / female type M orF:”); // to read some character
char ch=(char)[Link]();
[Link](“name:”+str); In this example we have used char in in brackets. This is
[Link](“age is :”+age); called typecasting. The read() method reads single
[Link](“ gender is :”+ch); character from the keyboard and returns the ASCII Vale
} and which is integer. To convert the integer to character
} we should use type casting in the code
2. Using Scanner class
The scanner class is a class in [Link] pacakge. The scanner class is introduced in Java 1.5. it will work
only if we have Jdk 1.5 onwards. The scanner class is a class used for scanning primitive types and strings.
It can be used to get input from an InputStream ([Link]),to parse trough a string o text or to read from
a file . The usage of scanner class is easy way to read input from file or console and code is cleaner.
Step3: Now, if the user has given the integer value from keyboard it is stored into the Scanner object(sc)
as a token. To recieve that token, we can use the method: sc nextInt(). To recieve string use [Link]( )
and recieve float use [Link](); methods.
%s – formats strings
%d – formatsintegers
%f – formats the floating-point numbers
%b- boolean
\n – new line character.
Types of casting: there are two types of casting, implicit Casting and Explicit Casting .
The implicit Casting is also called as automatic conversion or widening conversion. The
explicit casting is also called as narrowing conversion.
Implicit Casting
Automatic casting done by the java compiler internally is called implicit Casting. Implicit
Casting is done to convert lower data type into a higher data type.
● when one type of data is assigned to another type of variable an automatic type
conversion with take place if,
◆the two types are compatible
◆the destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For example , the
int type is always large enough to hold all valid byte values, and both int and byte ate
integer types, so an automatic conversion from byte to int can be applied .
For widening conversions the numeric types, integer and floating point types are
compatible with each other.
Eg int ¡;
float f;
¡=10;
f=¡; // assigned int to float
The implicit Casting rules are clearly understood from the below diagram
byte -> short -> char -> int -> long -> float -> double
In the above line it demonstratea that a byte can be assigned to a shorter float,but a double
cannot be assigned to float or int.
class Test
{
public static void main(String[] args)
{
int i = 100;
Output
Int value 100
Long value 100
Float value 100.0
Explicit Casting
The casting done by the programmer or developer is called explicit Casting. Explicit Casting is must
when converting from a higher ata type to a lower data type.
In this form typename is the name of the type we are converting to and value is an expression that
results in the value we want to convert.
Example:
1. double d=6.289;
int I =(int)d; // in the above code, the value of double 6.289 is converted to int 6 and te
assigned the integer value 6 to I.
Java program to illustrate explicit type conversion
class Test
{
public static void main(String[] args)
{
double d = 100.04;
Output
Output:
Double value 100.04
Long value 100
Int value 100
//Java program to illustrate Conversion of int and double to byte
class Test
{
Output:
public static void main(String args[])
Conversion of int to byte.
{
i = 129 b = 1
byte b;
Conversion of double to byte.
int i = 128;
D = 323.142 b = 69
double d = 323.142;
[Link]("Conversion of int to byte.");
//i%127
b = (byte) i;
[Link]("i = " + i + " b = " + b);
[Link]("\nConversion of double to byte.");
//d%127
b = (byte) d;
[Link]("d = " + d + " b= " + b);
}
}
• What are the Java Operators?
Operators in java
Arithimetic Operators:
• Arithmetic operators are used to perform
arithmetic operations on variables and data.
• 1. Addition(+): This operator is a binary
operator and is used to add two operands.
• num1 + num2
Example:
num1 = 10, num2 = 20 ;
sum = num1 + num2 ;
= 30
• 2. Subtraction(-): This operator is a binary operator and is used to subtract two operands.
• Syntax:
num1 - num2
• Example:
num1 = 20, num2 = 10 sub =
num1 - num2 = 10
3. Multiplication(*): This operator is a binary operator and is used to multiply two operands.
num1 * num2
Example:
num1 = 20, num2 = 10 mult = num1 * num2 = 200
• 4. Division(/): This is a binary operator that is used to divide the
first operand(dividend) by the second operand(divisor) and give the
quotient as a result.
• num1 / num2
• num1 = 20, num2 = 10 div = num1 / num2 = 2
• 5. Modulus(%): This is a binary operator that is used to return the
remainder when the first operand(dividend) is divided by the
second operand(divisor).
• Syntax:
• num1 % num2
• num1 = 5, num2 = 2 mod = num1 % num2 = 1
• public class ArithmeticOperator
• {
• public static void main(String[] args) Addition num1+num2 13
• { Subtraction num1-num2 -3
• int add, Multiplication num1*num2 40
• sub, Division num1/num2 0
• mul, Modulus num2%num1 3
• div,
• mod;
• int num1 = 5,
• num2 = 8;
• add = num1 + num2;
• sub = num1 - num2;
• mul = num1 * num2;
• div = num1 / num2;
• mod = num2 % num1;
• [Link]("Addition num1+num2 " + add);
• [Link]("Subtraction num1-num2 " + sub);
• [Link]("Multiplication num1*num2 " + mul);
• [Link]("Division num1/num2 " + div);
• [Link]("Modulus num2%num1 " + mod);
• }
2. Relation Operators
• Relational operators are used to check the relationship between two
operands.
• Relational operators are used in decision making and loops.
Logical Operators
• Logical operators are used to perform logical
“AND”, “OR” and “NOT” operations.
• fi. Logical ‘AND’ Operator (&&)
• This operator returns true when both
the conditions under consideration
are satisfied or are true. If even one of the
two. yields false, the operator results false
public class Land {
public static void main(String[] args) {
int x = 5;
InSimple terms, cond1 && cond2 returns true [Link](x > 3 && x < 10); // returns true becaus
when both cond1 and cond2 are true (i.e. non- is greater than 3 AND 5 is less than 10
zero). }
}
Syntax:
condition1 || condition2
The left side operand of the assignment operator is a variable and the right side operand of the assignment
operator is a value.
variable operator value;
Increment and Decrement Operators:
The increment (++) and decrement operator (--) are simply used to increase and decrease the
value by one.
Increment and decrement operators are unary operators. We can only apply these operators on a single
operand,hence these operators are called as unary operators.
Pre Increment Operator:(++x)
If an Increment operator is used in front of an operand, then it is called as Pre Increment operator.
This operator is used only for object reference variables. The operator checks whether the object is of a particular
type (class type or interface type). instanceof operator is written as −
( Object reference variable ) instanceof (class/interface type) If the object referred by the variable on the left
side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true.
Following is an example −
Example
Live
public class Test {
public static void main(String args[]) {
String name = "James"; // following will return true since name is type of String
Test ob1=new Test();
boolean result = name instanceOf String;
boolean result1 = ob1 instanceOf Test;
[Link]( result 1);
[Link]( result );
}}
This will produce the following result −
Output
true
true
New operator
The new operator is used to create objects,that is instances of classes
Eg: Animal dog=new Animal();
Dot operator
Their operator (.) is used to access the instance variables and methods of class using object
[Link];
[Link]();
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.
To create a Class
Syntax
Here elements between the pair of square brackets [] are optional . Access
modifiers are public, private, protected and class modifier is abstract which
are optional
Extends is the keyword used to create inheritance and implements is also
keyword to create interfaces(which will be studied later). Even variables
and methods are optional in class declaration.
Example
public class Dog {
String breed;
int age;
String color;
void barking() {
[Link](" Dog is baarking") ;
}
void hungry() {
[Link]("dog is feeling hungry") ;
}
void sleeping() {
[Link]("dog is sleeping") ;
}
}
Adding variables inside class
A class can have any number of methods to access the value of various
kinds of methods. In the above example, barking(), hungry() and sleeping()
are methods.
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.
To create a Class
Syntax
Here elements between the pair of square brackets [] are optional . Access
modifiers are public, private, protected and class modifier is abstract which
are optional
Extends is the keyword used to create inheritance and implements is also
keyword to create interfaces(which will be studied later). Even variables
and methods are optional in class declaration.
Example
public class Dog {
String breed;
int age;
String color;
void barking() {
[Link](" Dog is baarking") ;
}
void hungry() {
[Link]("dog is feeling hungry") ;
}
void sleeping() {
[Link]("dog is sleeping") ;
}
}
Adding variables inside class
A class can have any number of methods to access the value of various
kinds of methods. In the above example, barking(), hungry() and sleeping()
are methods.
Method definition consists of a method header and a method body. The same
is shown in the following syntax −
Syntax
•example
public static int methodName(int a, int b) {
// body
}
Method with return type and without return type
For using a method, it shld be called. There are two ways in which a method
is called i.e., method returns a value or returning nothing (no return value).
Java return keyword is used to complete the execution of a method and can
be used to return a value from a method. The return followed by the
appropriate value that is returned to the caller. This value depends on the
method return type like int method always return an integer value.. A return
type may be a primitive type like int, float, double and char. The type of data
returned by a method must be compatible with the return type specified by the
method. For instance, if the return type of some method is boolean, we can not
return an integer.
EXAMPLE of function returning a value
Typically, you will use a constructor to give initial values to the instance
variables defined by the class
All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor that initializes all member
variables to zero. However, once you define your own constructor, the
default constructor is no longer used.
Syntax
Following is the syntax of a constructor −
class ClassName {
ClassName() {
}
}
Class A{
Public void main(String args[]){
A a1=new A();
}}
Here A() is a constructor, this statement virtually means, asking jvm
to create object of class A by executing the constructor A() defined
in class A. When we compile the program, we get .class file, if the
.java file consists any constructor, then the .class file also will have
the same constructor. Suppose if the .java file does not have any
constructor defined in it, then the compiler adds a default
constructor with the name of the class into the .class file and it is
this default constructor that is going to get executed whenever the
JVM encounters the new operator and create an object for the
class.
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
You would call constructor to initialize objects as follows −
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
[Link](t1.x + " " + t2.x);
}
}
Java Environment
• The java environment contains both development tools and class libraries. The development tools are part of
Java development kit(Jdk) and class libraries are part of Java application programming interface(API).
• Javac – the compiler for the java programming [Link] this tool we can compile Java programs and it
generates byte code.
• Java - the launcher or interpreter , using this tool we can execute the java byte codes.
• Javadoc- API documentation generator . Using this tool we can generate documentation for our Java programs in
html format, which describes classes,methods, constructors and fields.
• Appletviewer-- using this tool we can run and debug applets without a web browser.
• Jar-- create and manage Java archive (jar ) files.
• Jdb– the java debugger . Using this tool we can debug our Java programs to find out any errors.
• Javah– c header and stub generator .used to write native methods.
• Javap– class file disassembler. Using this tool we can convert byte codes to a program description.
2) Java application interface (API)
The application programming interface are pre written Java code that can be used by other programmers
create Java applications. The java API is the set of huge number of classes and methods grouped into
packages and it is included with the java development environment .the most commonly used packages
are:
• [Link] : are language support package . These classes support the basic language features and the
handling of arrays and strings. Classes in this package are always available directly in our programs by
default because this package is always automatically loaded with out program.
• [Link]: classes for data input and Output Operations
• [Link]:this package contains utility classes for managing data within collections groups of data
items . It contain classes for time, date and random number generator
• [Link]: to implement applet programs
• [Link]: abstract window toolkit: classes in this package provide the original GuI components as well
as some basic support necessary for swing components..
• [Link]: classes related to develop network programs
• [Link]: these classes provide easy to use and flexible components for building graphical user
interface s. The components in this package are referred to as swing components.
[Link] : classes related to database access database connectivity.
The [Link] class contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square root, and
trigonometric functions.
Character class
Java provides a wrapper class Character in [Link] package. An object of type
Character contains a single field, whose type is char. The Character class offers a
number of useful class (i.e., static) methods for manipulating characters. You can
create a Character object with the Character constructor.
Syntax:
[Link]([Link]('A’)); //true
[Link]([Link](‘0’)); //false
2. boolean isDigit(char ch): This method is used to determine
whether the specified char value(ch) is a digit or not. Here also we can
pass ASCII value as an argument.
Syntax:
[Link]([Link]('0’)); //true
Syntax:
Syntax:
Syntax:
6. char toUpperCase(char ch): It returns the uppercase of the specified char value(ch). If
an ASCII value is passed, then the ASCII value of its uppercase will be returned.
Syntax:
Syntax:
1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string
constant pool" first. If the string already exists in the pool, a reference
to the pooled instance is returned. If the string doesn't exist in the pool,
a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be
created. Firstly, JVM will not find any string
object with the value "Welcome" in string
constant pool, that is why it will create a
new object. After that it will find the string
with the value "Welcome" in the pool, it will
not create a new object but will return the
reference to the same instance.
2) By new keyword
String s=new String("Welcome");//creates two objects and one
reference variable
In such case, JVM will create a new string object in normal (non-pool)
heap memory, and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in a heap (non-
pool).
Strings Methods and its Description
1) Java String length(): The Java String length() method tells the length of the
string. It returns count of total number of characters present in the String. For
example:
String s1="hello";
String s2="whatsup";
[Link]("string length is: "+[Link]());
[Link]("string length is: "+[Link]());
}}
Here, String length() function will return the length 5 for s1 and 7 for s2
respectively.
2) Java String concat() : The Java String concat() method combines a
specific string at the end of another string and ultimately returns a
combined string. It is like appending another string. For example:
String s1="hello";
s1=[Link]("how are you");
[Link](s1);
}}
The above code returns “hellohow are you”.
3) Java String Trim() : The java string trim() method removes the
leading and trailing spaces. It checks the unicode value of space
character (‘u0020’) before and after the string. If it exists, then
removes the spaces and return the omitted string. For example:
String s1=" hello ";
[Link](s1+"how are you"); // without trim()
[Link]([Link]()+"how are you"); // with trim()
}}
In the above code, the first print statement will print “hello how are
you” while the second statement will print “hellohow are you” using
the trim() function.
4)Java String toLowerCase() : The java string toLowerCase() method
converts all the characters of the String to lower case. For example:
In the above code, it will replace all the occurrences of ‘h’ to ‘t’.
Output to the above code will be “tello tow are you”.
int → Integer
double → Double
char → Character
boolean → Boolean
byte → Byte
short → Short
long → Long
float → Float
Autoboxing and Unboxing
Java automatically converts between primitives and their wrapper objects through a
feature called autoboxing and unboxing. Autoboxing is the automatic conversion of
a primitive to its wrapper object, while
unboxing is converting the wrapper back to a primitive.
Example:
Static method in Java is a method which belongs to the class and not
to the object. A static method can access only static data. It is a
method which belongs to the class and not to the object(instance). A
static method can access only static data. It cannot access non-
static data (instance variables).
A static method can call only other static methods and can not call a
non-static method from it.
A static method can be accessed directly by the class name and
doesn’t need any object
A static method cannot refer to "this" or "super" keywords in anyway
Syntax :
<class-name>.<method-name>
class SimpleStaticExample
{
// This is a static method
static void myMethod()
{
[Link]("myMethod");
}
- we can also have final object reference variable marked final can't
ever be reassigned to refer to a different object.
Eg final int a=100;
Final Methods
- the methods in the class can be declared as final. A method can be declared
final to prevent subclasses from overriding it. This the behaviour it implements
becomes unchangeble.
Eg: class A{
final void secure() {
[Link](" This is highly secure");
}
Void nonsecure{
[Link](" This is non secure superclass method") ;}
}
Class Demo extends A{
Void non secure() {
[Link](" This is non secure subclass") ;
}
}
Final Classes
- the key word final can also be used for classes. If we declare A class as final
then that class cannot be inherited. The final classes cannot be subclassed .
- if all the methods are highly secure and do not want anybody to override the
behavior then we can make entire class as final.
Typecasting
Typecasting is the process of converting one variable of certain datatype
into another datatype.
Types of casting: there are two types of casting, implicit Casting and
Explicit Casting . The implicit Casting is also called as automatic
conversion or widening conversion. The explicit casting is also called as
narrowing conversion.
Implicit Casting
Automatic casting done by the java compiler internally is called implicit
Casting. Implicit Casting is done to convert lower data type into a higher
data type.
● when one type of data is assigned to another type of variable an
automatic type conversion with take place if,
◆the two types are compatible
◆the destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For
example , the int type is always large enough to hold all valid byte values,
and both int and byte are integer types, so an automatic conversion from
byte to int can be applied .
For widening conversions the numeric types, integer and floating point
types are compatible with each other.
Eg int ¡;
float f;
¡=10;
f=¡; // assigned int to float
The implicit Casting rules are clearly understood
from the below diagram
Output
Int value 100
Long value 100
Float value 100.0
Explicit Casting
• One more use of this keyword is to resolve the name conflicts between
the method arguments and instance varibales. Let us assume that, we
have two instance variables called I and j. The constructor argument also
have the same name I and j. We want the constructor to set the values of
the argumnets to the instance varibales..
Class A{
int I, j;
A() {
}
A(int I, int j) {
I=I; // it is confusing which I is assigning to which i
J=J; // it is confusing, which j is assiging to which j
}
}
To avoid these conflicts, we can use this keyword as shown below.
Class A{
int i,j;
A() {
}
A(int i, int j) {
this.i=i; // it is confusing which I is assigning to which i
this.j=j; // it is confusing, which j is assiging to which j
}
}
Here this.i and this.j refers to instance variables and 'i' and 'j' refers
to method arguments
Class A{
int i, j;
Void function 1() {
int I=100;
[Link](i);
[Link](this.i) ;
}
}
Java Arrays
Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
[Link]([Link]);
// Outputs 4
Loop Through an Array
You can loop through the array elements with the for loop, and use the
length property to specify how many times the loop should run.
The following example outputs all elements in the cars array:
To create a two-dimensional array, add each array within its own set of curly
braces: