0% found this document useful (0 votes)
2 views11 pages

Java Basics

The document provides an overview of programming concepts including variables, data types, operators, control statements, and arrays. It explains primitive and non-primitive data types, various operators, and control structures such as conditional statements and loops. Additionally, it covers methods for input/output, sorting, and string manipulation.
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)
2 views11 pages

Java Basics

The document provides an overview of programming concepts including variables, data types, operators, control statements, and arrays. It explains primitive and non-primitive data types, various operators, and control structures such as conditional statements and loops. Additionally, it covers methods for input/output, sorting, and string manipulation.
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
You are on page 1/ 11

Variable is a container which can hold data and to represent data, we need variables.

DATA TYPES - Data type represents type of data.


1) Primitive - Stores actual values
byte, short, int, long -----> number without decimal
float, double -----> decimal number
char -----> single character (single quote)
boolean -----> true/false
2) Non-primitive/ Derived /Collections – Stores references to memory
String - ArrayList - HashMap - HashSet - Object
OPERATORS - Operator is a symbol which will perform an operation.
Operator Types -
1) Arithmetic operators +-*/%
2) Relational/comparison operators > >= < <= != ==
3) Logical operators && || !
4) Increment & Decrement operators ++ --
5) Assignment = += -= *= /= %=
6) conditional/ternary operator ?:
Unary Operators: ++ -- = += -= *= /= %= !
Binary operators: + - * / % > >= < <= != == && ||
ternary operator: ?:
Increment and Decrements Operators
post increment //10 pre increment //11
int a=10; int a=10;
int res=a++; int res=++a;
System.out.println(res); System.out.println(res);
post decrement //100 pre-decrement //99
int a=100; int a=100;
int res=a--; int res=--a;
System.out.println(res); System.out.println(res);
int res1=--res; //98
System.out.println(res1);
Assignment operators
int a=10; int a=10; int a=10; int a=10;
//a=a+5; a-=5; //a=a*2; a%=2;
a+=5; // a=a-5 a*=2; //a=a%2;
System.out.println(a); System.out.println(a) System.out.println(a) System.out.println(a)

Ternary Operator - var= exp ? result1 : result 2;


Example1 Example2 Example3
int a=100, b=200; int person_age=15; int x=(1==1)?100:200;
int res=(a>b)?a:b; String res=(person_age>=18)? "Eligible": "Not System.out.println(x);
System.out.println(res); eligible";
System.out.println(res);

CONTROL STATEMENTS
1) Conditional Statements
2) Looping/Iterative Statements -
3) Jumping Statements

Switch Case syntax int weekno=1;


switch(weekno)
Display week names based on week number {
case 1: System.out.println("Sunday"); break;
Datatype variable=data; case 2: System.out.println("Monday"); break;
switch(variable) case 3: System.out.println("Tuesday"); break;
{ case 4:System.out.println("Wednesday");break;
case value1: statements; break; case 5: System.out.println("Thursday"); break;
case value2: statements; break; case 6: System.out.println("Friday"); break;
default: statements; case 7: System.out.println("Saturday");break;
} default: System.out.println("Invalid week
number");
}
If : int person_age=20;
if(condition) if(person_age>=18)
{ {
statements; System.out.println("Eligible for vote");
} }
If..Else : int person_age=10;
if(condition) if(person_age>=18)
{ {
statements; System.out.println("Eligible for vote");
} }
else else
{ {
statements; System.out.println("Not eligible for vote");
} }
NumberPositiveNagitiveZero { EvenOrOddNumber {
int num=0; int num=11;
if(num>0) if(num%2==0)
{ {
System.out.println("Number is Positive"); System.out.println("Even number");
} }
else if(num<0) else
{ {
System.out.println("Number is Nagitive"); System.out.println("Odd number");
} }
else
{
System.out.println("Number is Zero");
}
Largest Of 3 Numbers int a=10, b=40,c=30;
Pre-requisite: all the numbers are having if(a>b && a>c)
di erent values {
a>b and a>c -- a is largest System.out.println("a is largest number");
b>a and b>c -- b is largest }
c>a and c>b -- c is largest else if(b>a && b>c)
{
System.out.println("b is largest number");
}
else
{
System.out.println("c is largest number");
}
If Else Ladder
PrintWeekNames {
int weekno=7; else if(weekno==5)

if(weekno==1) {System.out.println("Thursday");}

{System.out.println("Sunday");} else if(weekno==6)

else if(weekno==2) {System.out.println("Friday");}

{System.out.println("Monday");} else if(weekno==7)

else if(weekno==3) {System.out.println("Saturday");}

{System.out.println("Tuesday");} else

else if(weekno==4) {System.out.println("Invalid week number");}

{System.out.println("Wednesday");}

Looping statements : loop or iteration - executing same set of statements multiple times.

while(condition) do for(initilization; condition ; inc/dec )


{ { {
statements; statements; statements;
} } }
while(condition);
Example: Print 1.....10 Example : print 1...10 Example1 : 1....10
int i=1; //initialization int i=1; for(int i=1; i<=10; i++ )
while(i<=10) // condition do {
{ { System.out.println(i);
System.out.println(i); System.out.println(i); }
i++; // incrementation i++; Example2 : even numbers 1....10
} } for(int i=2; i<=10; i+=2 )
while(i<=10); {
System.out.println(i);
}
Example : Print 10 9 8 7 ...1 Example : Print Method 2
int i=10; 10.....1 for(int i=1; i<=10; i++ )
while(i>=1) int i=10; {
{ do if(i%2==0)
System.out.println(i); { {
i--; System.out.println(i); System.out.println(i);
} i--; }

}while(i>=1);
Jumping Statements
for (int i=1;i<=10;i++) for(int i=1;i<=10;i++) for(int i=1;i<=10;i++)
{ { {
if(i==5) if(i==5) if(i==5 || i==7 ||i==9)
{ { {
break; continue; continue;
} } }
System.out.println(i); System.out.println(i); System.out.println(i);
} } }
it will break and not it will skip the number 5 it will skip the number 5 7
proceed further after the and continue 9 and continue
condition //1 2 3 4 //1 2 3 4 6 7 8 9 10 // 1 2 3 4 6 8 10

for loop - enhanced for loop (for each loop)


This loop especially design for collections like arrays, list, HashMap.....
int a[]= {10,20,30,40,50};
for(int x:a) //will go to each and every value and print
{
System.out.println(x);
}

Arrays
Arrays - Array is collection of elements of same data type (Homogeneous data).
We can store multiple values into a single variable.
1) Single dimensional 2) Two Dimensional/Double dimensional
int a[]=new int[100]; here 100 is array size/ int a[][]=new int[3][2];
number of values we can store. int [][]a=new int[3][2];
int []a=new int[100]; int []a[]=new int[3][2];

1) Declare an array 2) add values into array 3) Find size of an array


4) read single value from an array 5) read multiple values from an array
Single Dimensional Array Two/Double Dimensional Array
1) Declaring array 1&2)Declaration & adding values
Appraoch1 : declaration Appraoch1 : declaration
int a[]=new int[5]; int a[][]=new int[3][2];
2) Adding values into array adding values
a[0]=10; a[0][0]=100;
a[1]=20; a[0][1]=200;
a[2]=30;
a[3]=40; a[1][0]=300;
a[4]=50; a[1][1]=400;
Appraoch2 : declaration + adding values
int a[]= {10,20,30,40,50}; a[2][0]=500;
System.out.println(a); a[2][1]=600;
// incorrect , should not use Appraoch2 : declaration + adding values
int a[][]= { {100,200}, {300,400}, {500,600} };
3) Find size of an array
System.out.println(a.length); 3) Find size of an array
//returns lenght(size) of an array 5 System.out.println(a.length);
// returns number of rows 3
4) read single value from an array System.out.println(a[0].length);
System.out.println(a[2]); //30 // returns number of columns in specific
System.out.println(a[0]); //10 row

5) read multiple values from an array 4) read single value from an array
System.out.println(Arrays.toString(a)); System.out.println(a[1][1]); //400
//[10, 20, 30, 40, 50]
5) reading data from 2D array
//normal for loop for(int i=0;i<=a.length-1;i++)
for(int i=0;i<=a.length-1;i++) {
{ for(int j=0;j<=a[i].length-1;j++ )
System.out.println(a[i]); {
} System.out.print(a[i][j]);
//[10, 20, 30, 40, 50] }
}
//enhanced for loop / for..each loop //Enhanced for loop
for(int value:a) for(int arr[]:a)
{ {
System.out.println(value); for(int x:arr)
} {
//[10, 20, 30, 40, 50] System.out.print(x);
}
}
//100 200 300 400 500 600
How to take input from keyboard/ at run time? Scanner
1) Seaching an element in array
2) Find how many times a number is repeated..
3) Find number of even's and odd's in array
4) Sort elements in array
5) Reverse an array
Scanner sc=new Scanner(System.in);
//Integer
System.out.println("Enter a number:");
int a= sc.nextInt();
System.out.println("Given value of a is:"+ a);
//Decimal
System.out.println("Enter a decimal number:");
double num=sc.nextDouble();
System.out.println("given decimal number is:"+num);
//String
System.out.println("Enter your name:");
String name=sc.next();
System.out.println("Your name is:"+name);

Sorting Elements in array


Sorting Numbers Sorting Strings
int a[]= {1,3,7,9,0,2,5,6}; String b[]= {"Z","B","M","X","A","V"};
System.out.println(Arrays.toString(a)); System.out.println("Before Sorting:" + Arrays.toString(b));
// [1, 3, 7, 4, 9, 0, 2, 5, 6] - Before Sorting Arrays.sort(b);
Arrays.sort(a); System.out.println("After Sorting:" + Arrays.toString(b));
System.out.println(Arrays.toString(a)); }
// [0, 1, 2, 3, 4, 5, 6, 7, 9] - After Sorting
ObjectTypeArray {

Object a[]=new Object[5]; Reverse a String


a[0]=100; Method1 - length(), charAt()
a[1]="welcome"; String s="selenium";
a[2]='A'; String rev="";
a[3]=true; for(int i=s.length()-1; i>=0; i--)
a[4]=10.5; {
System.out.println(Arrays.toString(a)); rev=rev+s.charAt(i);
}
[100, welcome, A, true, 10.5]
System.out.println("Reverse string :"+ rev);
OR
for(Object x:a)
{ Method2 - by converting string to char array
System.out.println(x); 100 String s="welcome";
} welcome String rev="";
A char a[]=s.toCharArray();
true // this will convert string to character type array
10.5 System.out.println(Arrays.toString(a));
//[w, e, l, c, o, m, e]
for(int i=a.length-1;i>=0;i--)
{
rev=rev+a[i];
}
System.out.println("Reverse string:"+ rev);

Reverse an Array Method3 - using StringBu er


int a[]= {10,20,30,50,40};
StringBu er s=new StringBu er("welcome");
using for loop System.out.println(s.reverse());
for(int i=4;i>=0;i--)
{
System.out.println(a[i]);
} Method4 - using StringBuilder
using while loop
int i=4; StringBuilder s=new StringBuilder("welcome");
while(i>=0) System.out.println(s.reverse());
{
System.out.println(a[i]);
i--;
}
String Methods :
String s="welcome"; length() - returns length of the string
OR String s="welcome";
String s=new String("welcome"); int l=s.length();
System.out.println(s); //welcome System.out.println(l); //7
System.out.println(s.length()); //7
concat() - join string replace() - replace single
String s1="welcome"; character/sequence of characters(string)
String s2="to java"; in a string
String s3="programming"; s="welcome to selenium java python";

System.out.println(s1+s2); System.out.println(s.replace('e','X'));
System.out.println(s1.concat(s2)); //wXlcomX to sXlXnium java python
//welcome to java
System.out.println(s1+s2+s3); System.out.println(s.replace("python","C
System.out.println(s1.concat(s2).concat(s3)); #"));
//welcome to java programming //welcome to selenium java C#
System.out.println("welcome"+"to java");
System.out.println("welcome".concat("to java"));

trim() - remove spaces right and left side charAt() - returns a character based on
String s=" welcome "; index
System.out.println("Before trimming:"+ s.length()); index starts from 0
//13 String s="welcome";
s1=s.trim(); System.out.println(s.charAt(3)); //c
System.out.println("After trimming:"+s1.length()); //7 System.out.println(s.charAt(5)); //m

contains() - returns true/false substring() - extract substring from the


check a string is part of the main string main string
String s="welcome"; String s="welcome";
System.out.println(s.contains("wel")); //true System.out.println(s.substring(2, 5)); //lco
System.out.println(s.contains("Come")); //false System.out.println(s.substring(1,3)); //el
System.out.println(s.contains("come")); //true
System.out.println(s.contains("welome")); //false

equals() , equalsIgnoreCase() toUpperCase() toLowerCase()


compare 2 strings and returns true/false converting case
String s1="welcome"; String s="Welcome";
String s2="welcome"; System.out.println(s.toUpperCase());
System.out.println(s1.equals(s2)); // true //WELCOME
System.out.println(s1.equals("Welcome")); //false System.out.println(s.toLowerCase());
System.out.println(s1.equalsIgnoreCase("Welcom //welcome
e")); //true
split() - split/divide the string in to multiple parts based on delimeter.
// * % ^ & ( ) - you cannot use as delimeters
Ex1 Ex2
String s="abc@xyz"; s="abc@gmail.com";

String a[]=s.split("@"); String a[]=s.split("@");


System.out.println(a[0]); //abc System.out.println(a[0]); //abc
System.out.println(a[1]); //xyz System.out.println(a[1]); //gmail.com

Ex3 - replace() Ex5


String amount="$15,20,55"; String s="abc 123 xyz";

System.out.println String arr[]=s.split(" ");


(amount.replace("$","").replace(",","")); System.out.println(Arrays.toString(arr));
//152055 //[abc, 123, xyz]

Ex4
String s="abc,123@xyz";
String a1[]=s.split(","); //abc 123@xyz
System.out.println(a1[0]); //abc
System.out.println(a1[1]); //123@xyz

String a2[]=a1[1].split("@"); //123 xyz


System.out.println(a2[0]); //123
System.out.println(a2[1]); //xyz
OR
String s="abc,123@xyz";
String firststring=s.split(",")[0];
String secondstring=s.split(",")[1].split("@")[0];
String thirdstring=s.split(",")[1].split("@")[1];
System.out.println(firststring); //abc
System.out.println(secondstring); //123
System.out.println(thirdstring); //xyz
String Comparison -
equals() equalsignoreCase()
String str1 = "Hello"; String str1 = "Hello";
String str2 = "Hello"; String str2 = "HELLO";
String str3 = "hello";
Syso (str1.equalsIgnoreCase(str2));
System.out.println(str1.equals(str2)); // true (ignores case)
// true
(System.out.println(str1.equals(str3));
// false (case-sensitive comparison)
compareTo() == Operator - checks if they refer to the
String str1 = "Hello"; same object in memory
String str2 = "Hello"; String str1 = "Hello";
String str3 = "Hi"; String str2 = "Hello";
String str3 = new String("Hello");
System.out.println(str1.compareTo(str2));
// 0 (strings are equal) System.out.println(str1 == str2);
System.out.println(str1.compareTo(str3)); // true (both point to the same object)
// positive (str1 > str3) System.out.println(str1 == str3);
System.out.println(str3.compareTo(str1)); // false (di erent objects in memory)
// negative (str3 < str1)

String Bu er and String builder : When dealing with frequent modifications to


strings.

String - Immutable StringBu er – Mutable String Builder – Mutable


Does not change original We can change We can change
value if apply anything on it.
Original value remains the StringBu er s=new StringBuilder s=new
same. StringBu er("welcome"); StringBuilder("welcome");

String s="welcome"; s.append(" to java"); s.append("to java");

s.concat("to java"); System.out.println(s); System.out.println(s);


//welcome to java //welcometo java
System.out.println(s);
//welcome

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy