[Go to site: main page, start]

0% found this document useful (0 votes)
6 views117 pages

Java Notes

The document provides an overview of Java programming, covering its history, features, and basic programming concepts such as data types, operators, conditional statements, and object-oriented programming principles. It highlights Java's platform independence, robustness, and security features, along with examples of Java code for practical understanding. Additionally, it discusses loops, arrays, and enums, emphasizing the importance of constructors, methods, and the String class.

Uploaded by

harrychimbota
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views117 pages

Java Notes

The document provides an overview of Java programming, covering its history, features, and basic programming concepts such as data types, operators, conditional statements, and object-oriented programming principles. It highlights Java's platform independence, robustness, and security features, along with examples of Java code for practical understanding. Additionally, it discusses loops, arrays, and enums, emphasizing the importance of constructors, methods, and the String class.

Uploaded by

harrychimbota
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

lOMoARcPSD|45112722

JAVA Notes

Programming in java (Lovely Professional University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Harry Chimbota (harrychimbota@[Link])
lOMoARcPSD|45112722

CSE 310 JAVA


UNIT i
Introduction to Java : History and Features of Java, Java
program structure, Writing simple Java class and main()
method, Command-line arguments, Understanding JDK, JRE
and JVM.
Data In the Cart : Using primitive data types, Type
conversion, Keywords, Identifiers, Variables, Access modifiers,
static keyword, Wrapper class Operators : Working with Bit-
wise, arithmetic, logical, and relational operators, Unary,
assignment and Ternary operator, Operator precedence .
Conditional Statements : Using if/else constructs and switch-
case statements.

 The history of java starts with the GREEN TEAM(Java team


members also called as green team). It is designed for
interactive [Link] independent programming
language.
 Java is platform-independent because it is different from
other languages like C, C++, etc. which are compiled into
platform-specific machines while Java is a write-once, run-
anywhere language.
 A platform is the hardware or software environment in
which a program runs.
 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.

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

 Java was developed by James Gosling, who is known as the


father of Java, in 1995.
 James Gosling, Mike Sheridan, and Patrick Naughton
initiated the Java language project in June 1991. The small
team of sun engineers called Green Team.
 Firstly, it was called "Greentalk" by James Gosling, and the
file extension was .gt.
 After that, it was called Oak and was developed as a part of
the Green project.
 Oak is a symbol of strength and chosen as a national tree of
many countries like the U.S.A, France, Germany, Romania,
etc.
 In 1995, Oak was renamed as "Java" because it was already
a trademarkby Oak Technologies.
 No explicit pointer
 Java Programs run inside a virtual machine sandbox
 Classloader: Classloader in Java is a part of the Java
Runtime Environment (JRE) which is used to load Java
classes into the Java Virtual Machine dynamically. It add
security by separating the package for the classes of the
local file system from those that are imported from network
sources.
 Bytecode Verifier: It checks the code fragments for illegal
code that can violate access rights to objects.
 Security Manager: It determines what resources a class can
access such as reading and writing to the local disk.
 Java is best known for security, with it we can develop virus
free systems.
ROBUST: = The English meaning of Robust is strong. Java is
robust because:

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

o It uses strong memory management.


o
o There is a lack of pointers that avoid security problems.
o Java provides automatic garbage collection which runs on
the Java Virtual Machine to get rid of objects which are not
being used by a Java application anymore.
o There are exception handling and type-checking
mechanisms in Java.
o All these points make Java robust.
Java is architecture-neutral because there are no
implementation-dependent features, for example, the size of
primitive types is [Link] C programming, int data type occupies
2 bytes of memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture. However, it occupies 4 bytes of memory
for both 32 and 64-bit architectures in Java.
JAVA is portable= Java is portable because it facilitates you to
carry the Java bytecode to any platform. It doesn't require any
implementation.
JAVA is an interpreted language which is why it is slower than
compiled languages, e.g., C, C++, etc.
JAVA is a dynamic language. It means classes are loaded on
demand. It supports dynamic loading of classes.
MULTI-THREADED: A thread is like a separate program, executing
concurrently.
We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading
is that it doesn't occupy memory for each thread. It shares a

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

common memory area. Threads are important for multi-media,


Web applications, etc.
SAMPLE PRORAM
import [Link]; //or we can use
import [Link].*;

public class sample {


public static void main(String[]
args) {
Scanner sc = new
Scanner([Link]);

[Link]("Enter Name: ");


String name = [Link]();

[Link]("Enter Age: ");


int age = [Link]();

[Link]("Enter Salary:
");
double salary = [Link]();

[Link]("\nEmployee
Details:");
[Link]("Name: " +
name);
[Link]("Age: " +
age);
[Link]("Salary: " +
salary);

[Link]();

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Primitive Datatypes, Type Conversion

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Keywords, Identifiers, Variables, Access Modifiers

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

public class variable {


static int x = 3; //CLASS
public static void main(String[]
args){
int x = 1; //LOCAL
System. [Link](x);
doSomething();
}
static void doSomething(){
int x = 2; //LOCAL
System. [Link](x);
}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Derclared inside class not inside method


Class test {
Int a = 5; //instance variables
float pi = 3.14; }
They always get a default value of 0.
They cannot be reinitialized within a class,but can
be reinitialized in a method.
class Test{ class Test{
int data =15; int data =15;
data = 20; //error void someMethod( ){
} data = 20; //allowed
} }

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

 Static int data = 10; only one copy is


created in class. What do u mean by one copy
defines below:

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

WRAPPER CLASSES
public class WrapperClasses {

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

public static void main(String[]


args) {
// Autoboxing
Integer a = 123;
Double b = 3.14;
Character c = '$';
Boolean d = true;

// Unboxing
int A = a;
double B = b;
char C = c;
boolean D = d;

[Link]("Autoboxed
values:");
[Link]("a (Integer) =
" + a);
[Link]("b (Double) =
" + b);
[Link]("c (Character)
= " + c);
[Link]("d (Boolean) =
" + d);

[Link]("\nUnboxed
values:");
[Link]("A (int) = " +
A);
[Link]("B (double) =
" + B);
[Link]("C (char) = "
+ C);

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

[Link]("D (boolean) =
" + D);
}
}

/*public class WrapperClasses {


public static void main(String[]
args) {
String a = [Link](123);
String b = [Link](3.14);
String c =
[Link]('@');
String d =
[Link](false);

String X =a + b + c + d;
[Link](X);
}
} */

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

OPERATORS

Types of Operators in Java


1. Arithmetic Operators 2. Ternary Operator
3. Unary Operators 4. Assignment Operator
5. Bitwise Operators 6. Relational Operators
7. Shift Operators 8. Logical Operators
9. Instance of operator :

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

UNIT II
Loops : Working with for loop, while loop, do-while
loop and for-each loop
Arrays and Enums : Fundamentals about Arrays, Multi-
dimensional arrays, Array Access and Iterations, Using
varargs, Enumerations
OOP Concepts : Basics of class and objects, Writing
constructors and methods, Overloading methods and
constructors, this keyword, initializer blocks
String Class : Constructors and methods of String and
String Builder class

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

class array{
public static void main(String[] args){
String[] fruits = {"apple", "orange", "banana"};
String[] vegetables = {"potato", "onion", "carrot"};
String[] meats = {"chicken", "pork", "beef", "fish"};

String [][] groceries = {fruits, vegetables, meats};

//String[1[] groceries = {{"apple", "orange", "banana"},


// {"potato"”, "onion", "carrot"},
// {"chicken", "pork", "beef", "fish"}};

groceries[0][0] = "pineapple";
for(String[] foods : groceries){
for(String food : foods){
[Link](food + " ");
}
[Link]();
}
}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

class array{
public static void main(String[]
args){

char[][] telephone = {{'1', '2',


'3'},
{'4', '5',
'6'},
{'7', '8',
'9'},
{'*', '0',
'#'}};

for(char[] row : telephone){


for(char number : row){
[Link](number
+ " ");
}
[Link]();
}
}
}
OUTPUT :
PS C:\Users\Adikeshava\OneDrive\Desktop\CSE 310 JAVA\
java> cd "c:\Users\Adikeshava\OneDrive\Desktop\CSE 310
JAVA\java\" ; if ($?) { javac [Link] } ; if ($?) { java array }
123
456
789
*0#

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

[Link] =it is used to sort the array elements in


ascending or descending.
[Link] = it fills the array with the given value.
Use this ,import [Link].
import [Link];
class array{
public static void main(String[] args){
String[] fruits = {"apple", "orange", "banana",
"coconut"};

[Link](fruits);
[Link](fruits, "strawberry");

for(String fruit : fruits){


[Link](fruit);
}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

class array{
public static void
main(String[] args){
String[] fruits = {"apple",
"orange", "banana", "coconut"};
// for(int i = 0; i <
[Link]; i++){
//
[Link](fruits[i] + "
");

for(String fruit : fruits){

[Link](fruit);
}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Example of user input Array :


import [Link];

public class Array {


public static void main(String[]
args) {
Scanner sc = new
Scanner([Link]);

[Link]("Enter the
number of food items: ");
int n = [Link]();

[Link]();

String[] foodArray = new


String[n];

for (int i = 0; i < n; i++) {


[Link]("Enter food
item #" + (i + 1) + ": ");
foodArray[i] = [Link]();
}

[Link]("\nFood Items
Entered:");
for (String food : foodArray) {
[Link](food);
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

[Link]();
}
}

import [Link];

public class ArrayInputExample {


public static void
main(String[] args) {
Scanner sc = new
Scanner([Link]);

// Ask the user for the


size of the array
[Link]("Enter
the size of the array: ");
int size = [Link]();

// Clear the buffer before


reading strings (this is needed
after using nextInt())
[Link]();

// Create an array of
Strings based on the size

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

String[] fruits = new


String[size];

// Prompt the user to


enter the elements of the array
[Link]("Enter
" + size + " fruit names:");

// Loop to read each


element of the array
for (int i = 0; i < size;
i++) {

[Link]("Enter fruit " +


(i + 1) + ": ");
fruits[i] =
[Link](); // Read a string
input and store it in the array
}

// Print the array


elements
[Link]("\
nFruits entered by the user:");
for (String fruit :
fruits) {

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

[Link](fruit);
}

[Link](); // Close the


scanner
}
}

VARARGS(VARIABLE ARGUMENTS)

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

// varargs = allow a method to accept a


varying # of arguments
// makes methods more flexible, no need
for overloaded methods
// java will pack the arguments into an
array
//(ellipsis)
class varargs{
public static void main(String[]
args){
[Link](add(1, 2, 3, 4, 5,
6));
[Link](add(5,
6,54,35,33));

[Link](aver(54,35,33,
28));

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

static int add(int... numbers){ //


(datatype... variable is called varargs)
int sum = 0;
for(int number : numbers){
sum += number;
}
return sum;
}

static double aver(int... numbers){


int sum = 0;
for(int number : numbers){
sum += number;
}
return sum / [Link];
}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

public class enumweek {

enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY;
}

public static void main(String[] args) {


Day today = [Link];

[Link]("Today is: " + today);

[Link]("\nThe days of the


week are:");
for (Day day : [Link]()) {
[Link](day);
}
[Link]("\nThe index of " +
today + " is: " + [Link]());
}
}

CLASSES AND OBJECTS

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

// Object = An entity that holds data (attributes) and


can perform actions (methods) .It is a reference data
type
public class object{
public static void main(String[]
args){

Car car = new Car();

[Link]([Link]);

[Link]([Link]);
[Link]([Link]);

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

[Link]([Link]);

[Link]([Link]);
[Link]();

[Link]([Link]);
[Link]();

[Link]([Link]);

[Link]();
[Link]();
}

public static class Car {


String make = "Ford";
String model = "Mustang";
int year = 2025;
double price = 58000.99;
boolean isRunning = false;

void start(){
isRunning = true;
[Link]("You start
the engine");
}
void stop(){

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

isRunning = false;
[Link]("You
stop the engine");
}

void drive(){
[Link]("You
drive the " + model);
}
void brake(){
[Link]("You
brake the " + model);
}
}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

CONSTRUCTORS AND METHODS

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

// method = a block of reusable code that is executed when called ()


/* public class method {
public static void main(String[] args){

happyBirthday();
happyBirthday();
happyBirthday();
}
static void happyBirthday(){
[Link]("Happy Birthday to you!");
[Link]("Happy Birthday dear you!");
[Link]("You are x years old!");
[Link]("Happy Birthday to you!\n");
}
} */

/* public class method {


public static void main(String[] args){

String name = "babu";


int age = 45;
happyBirthday(name,age); //arguments
}

static void happyBirthday(String name, int age){ //parameters


[Link]("Happy Birthday to you!");
[Link]("Happy Birthday dear %s!\n",name);
[Link]("You are %d years old!”, age);
[Link]("Happy Birthday to you!\n");
}
} */

// here the parameters can be different from arguments


/* public class method {
public static void main(String[] args){

String name = "babu";


int age = 45;
happyBirthday(name,age); //arguments
}

static void happyBirthday(String birthdayboy, int age){


//parameters
[Link]("Happy Birthday to you!");
[Link]("Happy Birthday dear %s!\n",birthdayboy);
[Link]("You are %d years old!",age);
[Link]("Happy Birthday to you!\n");
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

} */

public class method {


public static void main(String[] args){

[Link](square(5));
[Link](cube(5));
String fullName = getFullName("Spongebob", "Sguarepan");
[Link](fullName);
int age = 21;
if(ageCheck(age)){
[Link]("You may sign up!");
}else{
[Link]("You must be 18+ to sign up");
}

static void happyBirthday(String birthdayboy, int age){


//parameters

[Link]("Happy Birthday to you!");


[Link]("Happy Birthday dear %s!\n",birthdayboy);
[Link]("You are %d years old!",age);
[Link]("Happy Birthday to you!\n");
}
static double square(double number){
return number * number;
}
static double cube(double num){
return num * num * num;
}
static String getFullName(String first, String last){
return first + " " + last;
}
static boolean ageCheck(int age){
if(age >= 18){
return true;
}
else {
return false;
}
}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

/*
* overloaded methods = methods that share the
same name,but different parameters
* signature = name + parameters
public class method {
public static void main(String[] args){
[Link](add(1,2,8));
}

static double add(double a, double b){


return a + b;
}
static double add(double a, double b,double
c){
return a + b + c;
}
}
*/

public class method {


public static void main(String[] args){
String pizza = bakePizza("flat bread",
"mozzarella", "pepperoni");
[Link](pizza);
}

static String bakePizza(String bread){


return bread + " pizza";
}
static String bakePizza(String bread,String
cheese){
return cheese + " " + bread + " pizza";
}
static String bakePizza(String
bread,String cheese,String toppings){
return toppings + " " + cheese + " "
+ bread + " pizza";
}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

/*constructor = A special method to initialize


objects
You can pass arguments to a constructor and
set up initial values */
public class constructor{
public static void main(String[] args) {

// Creating objects of Student


Student student1 = new Student("Adhi",
20, 8.0);
Student student2 = new Student("Sai",
21, 7.5);
Student student3 = new
Student("chandhu", 21, 9.5);

// Printing out names of students


[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

[Link]([Link]);
[Link]();
[Link]();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

[Link]([Link]);
[Link]();
[Link]();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

[Link]([Link]);
[Link] ();

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

}
}

class Student {
// Instance variables
String name;
int age;
double gpa;
boolean isEnrolled;

// Constructor to initialize the


student object
Student(String name, int age, double
gpa){
[Link] = name;
[Link] = age;
[Link] = gpa;
[Link] = true;

//instead of this kw we can use


object created as follows
//[Link] = name;
//[Link] = age;
//[Link] = gpa;
//[Link] = name;
//[Link] = age;
//[Link] = gpa;
}

void study(){
[Link]([Link] + "
is studying");
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

public class const_overloading {


public static void main(String[]
args) {

// Creating objects of Student


User user1 = new
User("Spongebob");
User user2 = new User("Mahesh
Babu", "babu@[Link]");
User user3 = new User("Sai",
"sai@[Link]", 30);
User user4 = new User();

[Link]([Link]);

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

[Link]([Link]);
[Link]([Link]);
[Link]();

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}

class User{
// Instance variables
String userName;
String email;
int age;

// Constructor to initialize the


student object
User(){
[Link] = "Guest";

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

[Link] = "Not provided";


[Link] = 0;
}

User(String userName){
[Link] = userName;
[Link] = "Not provided";
[Link] = 0;
}

User (String userName, String


email){
[Link] = userName;
[Link] = email;
[Link] = 0;
}

User (String userName, String


email, int age){
[Link] = userName;
[Link] = email;
[Link] = age;
}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

class stringExample {
public static void main(String [] s){
String l1 = "I love java";
String s1 = new String ("I love java");

String l2 = "I love java";


String s2 = new String ("I love java");

[Link]("Through literal 1 " +


l1);
[Link]("Through new keyword 1
" + s1);
[Link]("Through literal 2 " +
l2);
[Link]("Through new keyword 2
" + s2);
[Link]();

[Link]("comparing string and


string" + (s1 == s2));
[Link]("comparing string and
literal" + (s1 == l1));
[Link]("comparing literal and
literal" + (l1 == l2));
[Link]("comparing literal and
string" + (l2 == s1));
[Link]();

[Link]([Link]("Thursday!"));
[Link]([Link](l1));
[Link]([Link](l2));
[Link]([Link](s2));
[Link]("Tim".equals("Jim"));

String str = new String();

String mystr = new String("Hello!");


String mystr1 = new String(mystr);

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

[Link]();
String l1 = "I love java";
and String l2 = "I love java";: Here,
l1 and l2 are string literals. In Java, string literals
are stored in a special area called the String Pool.
If a string literal already exists in the pool, the new
reference will point to the same memory location.
String s1 = new String("I love java"); and
String s2 = new String("I love java"): These strings
are created using the new keyword, which forces
the creation of a new string object in the heap,
even if the value is the same as one already in the
string pool.
The [Link]() statements
simply print the values of the variables (l1, s1, l2,
s2), showing the string content stored in those
variables. It will print the string "I love java" four
times, but the key difference is where the strings
are stored (string pool or heap).
The == operator checks if two references
point to the same memory location (not if the
content is the same). This is important to
understand when comparing strings in Java.

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

public class StringConstructorExample {


public static void main(String[] args) {
String emptyString = new String();
[Link]("Empty String: " + emptyString);

String originalString = "Hello World!";


String copiedString = new String(originalString);
[Link]("Copied String: " + copiedString);

//Creating a string from a byte using default encoding


byte[] byteArray = {72, 101, 108, 111}; //ASCII values of "Hello !
String byteString = new String(byteArray);
[Link]("String from Byte Array: " + byteString);

//Creating a String from a character array


char[] charArray = {'J', 'a', 'v', 'a'};
String charString = new String(charArray);
[Link]("String from Character Array: " + charString);
} }

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

The charAt(int index) method returns the character at the


specified index of the string. String indices in Java are 0-
based, meaning the first character has index [Link] Java, the
String class provides a wide range of methods to
manipulate and perform operations on strings. Here is a
list of common and useful String methods in Java:
1. Length-related Methods
• length()=Returns the length of the string (the number
of characters).
• String str = "Hello";
• int len = [Link](); // 5
2. String Comparison Methods = equals(Object obj)
Compares the content of two strings for equality (case-
sensitive).
• String str1 = "hello";
• String str2 = "hello";
• boolean isEqual = [Link](str2); // true
equalsIgnoreCase(String anotherString) = Compares the
content of two strings for equality, ignoring case
differences.
• String str1 = "hello";
• String str2 = "HELLO";

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

• boolean isEqual = [Link](str2); //


true
compareTo(String anotherString) = Compares two
strings lexicographically (case-sensitive). Returns a
negative integer, zero, or a positive integer depending
on whether the first string is lexicographically less than,
equal to, or greater than the second string.
• String str1 = "apple";
• String str2 = "banana";
• int result = [Link](str2); // Negative value
(str1 is less than str2)
compareToIgnoreCase(String anotherString) =
Compares two strings lexicographically, ignoring case
differences.
• String str1 = "apple";
• String str2 = "APPLE";
• int result = [Link](str2); // 0
(they are equal ignoring case)
3. Substring Methods = substring(int beginIndex)
Returns a new string that is a substring from the
specified index to the end.
• String str = "Hello, World!";

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

• String substr = [Link](7); // "World!"


substring(int beginIndex, int endIndex) = Returns a
substring from the specified start index to the specified
end index (exclusive).
• String str = "Hello, World!";
• String substr = [Link](7, 12); // "World"
4. Character Search Methods
charAt(int index) = Returns the character at the
specified index.
• String str = "Hello";
• char ch = [Link](1); // 'e'
indexOf(int ch) = Returns the index of the first
occurrence of the specified character.
• String str = "Hello, World!";
• int index = [Link]('o'); // 4
indexOf(String str) = Returns the index of the first
occurrence of the specified substring.
• String str = "Hello, World!";
• int index = [Link]("World"); // 7
lastIndexOf(int ch) = Returns the index of the last
occurrence of the specified character.
• String str = "Hello, World!";

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

• int index = [Link]('o'); // 8


lastIndexOf(String str) = Returns the index of the last
occurrence of the specified substring.
• String str = "Hello, World!";
• int index = [Link]("o"); // 8
5. String Manipulation Methods
toLowerCase() = Converts all characters in the string to
lowercase.
• String str = "Hello";
• String lower = [Link](); // "hello"
toUpperCase() = Converts all characters in the string to
uppercase.
• String str = "Hello";
• String upper = [Link](); // "HELLO"
trim() = Removes leading and trailing whitespace from
the string.
• String str = " Hello ";
• String trimmed = [Link](); // "Hello"
replace(char oldChar, char newChar) = Replaces all
occurrences of the specified character with a new
character.
• String str = "Hello, World!";

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

• String newStr = [Link]('o', 'a'); // "Hella,


Warld!"
replace(String oldStr, String newStr) = Replaces all
occurrences of the specified substring with a new
substring.
• String str = "Hello, World!";
• String newStr = [Link]("World", "Java"); //
"Hello, Java!"
6. String Splitting and Joining
split(String regex) = Splits the string into an array of
substrings based on the specified regular expression.
• String str = "apple,banana,orange";
• String[] fruits = [Link](","); // ["apple", "banana",
"orange"]
join(CharSequence delimiter, CharSequence...
elements) = Joins the elements of the given array or
collection into a single string with the specified
delimiter.
• String[] fruits = {"apple", "banana", "orange"};
• String result = [Link](", ", fruits); // "apple,
banana, orange"
7. String Formatting Methods

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

format(String format, Object... args) = Returns a


formatted string using the specified format string and
arguments.
• String formatted = [Link]("Hello, %s!",
"John"); // "Hello, John!"
valueOf(Object obj) = Converts any object to a string (if
the object is null, it returns the string "null").
• int num = 42;
• String str = [Link](num); // "42"
8. Checking String Properties
isEmpty() = Returns true if the string is empty (i.e., its
length is 0).
• String str = "";
• boolean isEmpty = [Link](); // true
contains(CharSequence sequence) = Returns true if the
string contains the specified sequence of characters.
• String str = "Hello, World!";
• boolean contains = [Link]("World"); // true
startsWith(String prefix) = Returns true if the string
starts with the specified prefix.
• String str = "Hello, World!";

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

• boolean startsWith = [Link]("Hello"); //


true
endsWith(String suffix) = Returns true if the string ends
with the specified suffix.
• String str = "Hello, World!";
• boolean endsWith = [Link]("World!"); //
true
9. String Conversion Methods
toCharArray() = Converts the string to a new character
array.
• String str = "Hello";
• char[] charArray = [Link](); // ['H', 'e', 'l',
'l', 'o']
intern() = Returns a canonical representation of the
string from the string pool. If the string already exists in
the pool, it returns the reference to the existing one;
otherwise, it adds the string to the pool and returns it.
• String str1 = new String("hello");
• String str2 = [Link](); // Returns the string
from the string pool
Index: 0 1 2 3 4 5 6 7 8 9 10
String: "I" " " "l" "o" "v" "e" " " "j" "a" "v" "a"

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

[Link]([Link]("Thursday!"));
[Link]([Link](l1));
[Link]([Link](l2));
[Link]([Link](s2));
[Link]("Tim".equals("Jim"));

String str = new String();

String mystr = new String("Hello!");


String mystr1 = new String(mystr);

[Link]();

//methods of string class

[Link]([Link](2));
[Link]("Holiday".charAt(2));

[Link]([Link]());

[Link]([Link](3));
[Link]([Link](3,7));

[Link]([Link]("Java"));

[Link]([Link]());
[Link]([Link]());

// String s1 = [Link]("Thurs","Fri"); this one is


wrong

String replaced = [Link]("love", "am addicted to");


[Link](replaced);

[Link]();

[Link]([Link]());

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

[Link]([Link]('a')); // first occurance


of character
[Link]([Link]('a')); // last
occurance od character
[Link]();
[Link]("bat".compareTo("hat")); // returns -
ve value
[Link]("hat".compareTo("bat")); // returns
+ve value
[Link]("cat".compareTo("cat")); // returns
zero value
[Link]();

[Link]([Link](" today"));
String new1 = "Good";
String new2 = "Afternoon";
String res = new1+new2;
[Link](res);
[Link]();

[Link]([Link](3));
[Link]();

[Link]("Winters".equals("winters"));

[Link]("Winters".equalsIgnoreCase("winters"));
[Link]();

[Link]("I hate java ".trim());


[Link]();

String newstr = "apple,kiwi,orange,banana";


String []fruits = [Link](",");
for(String i : fruits){
[Link](i);
}
[Link]();

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

String newstr1 = "cucumber ,strawberry ,watermelon


,banana ";
String []fruit = [Link](",");
for(String i : fruit){
[Link]([Link]());
}

UNICODE
The Unicode value for the uppercase letter 'A' is 65, and the
Unicode values for the subsequent uppercase letters increment
by 1, with 'B' being 66, 'C' being 67, and so on, until 'Z' which
has a Unicode value of 90.
For lowercase letters, the Unicode value of 'a' is 97, and the
values increase by 1 for each successive letter. Thus, 'b' has a
Unicode value of 98, 'c' has 99, and so on, until 'z', which has a
Unicode value of 122.
The difference between the Unicode values of corresponding
uppercase and lowercase letters is 32. For example, 'A' (Unicode
65) and 'a' (Unicode 97) differ by 32, and similarly, 'B' (Unicode
66) and 'b' (Unicode 98) also differ by 32, and this pattern
continues for the entire alphabet.
In summary, uppercase letters range from 65 ('A') to 90 ('Z'),
and lowercase letters range from 97 ('a') to 122 ('z'), with each
lowercase letter having a Unicode

Java StringBuilder Class


In Java, StringBuilder class is a part of
the [Link] package .

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

The StringBuilder class in Java is used to create mutable


(modifiable) strings. Unlike the String class, which creates
immutable strings (where any modification creates a new string
object), StringBuilder allows you to modify a string without
creating new objects each time. This makes StringBuilder more
efficient when performing multiple string manipulations, such as
appending, inserting, or modifying characters.

Commonly Used Methods of `StringBuilder =

[Link](String str)= Purpose: Appends the given string to the end of the
`StringBuilder`.

- Example:

StringBuilder sb = new StringBuilder("Hello");

[Link](" World");

[Link](sb); // Output: Hello World

[Link](int offset, String str)=Purpose: Inserts the given string at the


specified position (offset) in the `StringBuilder`.

- Example:

StringBuilder sb = new StringBuilder("Hello World");

[Link](5, ",");

[Link](sb); // Output: Hello, World

[Link](int start, int end)= Purpose: Deletes the characters between the
specified start and end indexes (start is inclusive, end is exclusive).

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

- Example:

StringBuilder sb = new StringBuilder("Hello World");

[Link](5, 11);

[Link](sb); // Output: Hello

[Link](int start, int end, String str) - Purpose: Replaces the


characters between the specified start and end indexes with
the given string.

- Example:

StringBuilder sb = new StringBuilder("Hello World");

[Link](6, 11, "Java");

[Link](sb); // Output: Hello Java

[Link]() - Purpose: Reverses the characters in the


`StringBuilder`.

- Example:

StringBuilder sb = new StringBuilder("Hello");

[Link]();

[Link](sb); // Output: olleH

[Link]() - Purpose: Returns the current capacity (size) of


the StringBuilder's internal character array.

- Example:

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

StringBuilder sb = new StringBuilder();

[Link]([Link]()); // Default capacity is 16

[Link]("Hello");

[Link]([Link]()); // Still 16 (unless the


string exceeds the initial capacity)

[Link]() - Purpose: Converts the `StringBuilder` to a


`String` object.

- Example:

StringBuilder sb = new StringBuilder("Hello");

String str = [Link]();

[Link](str); // Output: Hello

[Link](int index)= - Purpose:** Returns the character at


the specified index.

- Example:

StringBuilder sb = new StringBuilder("Hello");

[Link]([Link](1)); // Output: e
public class stringBuilder{
public static void main(String[] args) {
StringBuilder stb = new StringBuilder(" Chandragiri
Keshava");
[Link](13, "Adhi");
[Link](stb);
String s1 = [Link]();
[Link]([Link]());

Downloaded by Harry Chimbota (harrychimbota@[Link])


lOMoARcPSD|45112722

String s2 = [Link]();
String [] names = [Link](" ");
for(String n : names){
[Link](n);
}
}
}

public class stringBuilder{


public static void main(String[] args) {
StringBuilder stb = new StringBuilder("Rainy Day");
[Link](6, "Rainbow ");
[Link](stb);

String s1 = [Link]();
[Link](s1);
[Link]();

StringBuilder stb2 = new StringBuilder();


for (int i = 0; i < 5; i++) {
[Link](s1);
}

[Link]([Link]());
}
}

Downloaded by Harry Chimbota (harrychimbota@[Link])

You might also like