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

Java Basics Batch30

The document contains code snippets demonstrating various Java programming concepts such as: 1. Declaring and initializing variables of different primitive data types and performing arithmetic operations on them. 2. Printing out the minimum and maximum values that can be stored in byte, short, int and long primitive data types. 3. Examples of logical operators, conditional statements like if-else, switch case, ternary operator. 4. Iteration statements like for, while, do-while loops and examples of iterating over ranges. 5. Examples of unary, bitwise operators, string operations. 6. Methods to check if a year is a leap year, find maximum of 3 numbers, count digits

Uploaded by

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

Java Basics Batch30

The document contains code snippets demonstrating various Java programming concepts such as: 1. Declaring and initializing variables of different primitive data types and performing arithmetic operations on them. 2. Printing out the minimum and maximum values that can be stored in byte, short, int and long primitive data types. 3. Examples of logical operators, conditional statements like if-else, switch case, ternary operator. 4. Iteration statements like for, while, do-while loops and examples of iterating over ranges. 5. Examples of unary, bitwise operators, string operations. 6. Methods to check if a year is a leap year, find maximum of 3 numbers, count digits

Uploaded by

manikanta tarun
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

[ ] double d = 7%5/2;

System.out.println(d);

[ ] System.out.println("Byte min:"+Byte.MIN_VALUE);
System.out.println("Byte max:"+Byte.MAX_VALUE);
System.out.println("Short min:"+Short.MIN_VALUE);
System.out.println("Short max:"+Short.MAX_VALUE);
System.out.println("Int max:"+Integer.MIN_VALUE);
System.out.println("Int max:"+Integer.MAX_VALUE);
System.out.println("Long mix:"+Long.MIN_VALUE);
System.out.println("Long max:"+Long.MAX_VALUE);

[ ] //Is a given year a leap year?


//A. Yes if its century and divisible by 400 otherwise divisible by 4
//i.e if either (i) divisible by 400 or (ii) divisible by 4 but not 100
//Java progam using only logical operator and mod.

//int year = 2004;


int year = 2005;
boolean leap;
leap = (year%400==0)||((year%4==0)&&(year%100!=0));
System.out.println(leap);

[ ] //unary operators ++/--


int a=4;a++;++a;
System.out.println(a++);
System.out.println(++a);

[ ] int j=5;
int k=++j+j++; // j+=1;k = j+j; j=j+1
System.out.println(j+" "+k);
//byte b = 127;
//System.out.println(++b);

[ ] // >> << shift >>>

1028>>4; // 1028/4 = 257


// 100000-> 2 = 100000/10^2
8 << 2;

//32 >>2;

//00001000 ->2 8/2^2 = 8/4=2


//11110111
//11111000 //-8
//00111110
[ ] System.out.println(2 + 3 + "bc");
System.out.println((2+3) + "bc");
System.out.println("bc" + (2+3));
System.out.println("bc" + 2 + 3);

[ ] public class {
public static void main () {

}
}

[ ] double a = 3.14159;
System.out.println(a);
System.out.println(a + 1);
System.out.println(8 / (int) a);
System.out.println(8 / a);
System.out.println((int) (8 / a));
double x = 4;
int x = 3.5;

Conditionals to change the path of execution


if (condition) {do something}
else {do something}

    Income range   Tax rate


    0 - 47,450       22%
47,450 – 114,650     25%
114,650 – 174,700     28%
174,700 – 311,950     33%
311,950 >=           35%

[ ] int income=50000;
double rate;
if (income < 47500) rate = 0.22;
else {if (income < 114650) rate = .25;
else {if (income < 174700) rate = 0.28;
else {if (income <311950) rate = 0.33;
else rate = 0.35;
}
}
}
System.out.println(rate);

[ ] // is anything wrong with it.


int income=50000;
double rate = 0.35;
if (income < 311950) rate = 0.33;
if (income < 174700) rate = 0.28;
if (income < 114650) rate = 0.25;
if (income < 47450) rate = 0.22;

System.out.println(rate);

[ ] int dow=2;
if (dow==0)System.out.println("Sunday");
else if (dow==1)System.out.println("Monday");
else if (dow==2)System.out.println("Tuesday");
else System.out.println("Thursday");

[ ] String Dow = "Tue"; // 0-1 -Sunday2-3 monday


//float dow=3.0f;
switch(Dow) {
case "Mon":
case "Tue":
case "Wed": System.out.println("2"); break;
default: System.out.println("3");
}
//System.out.println(dow);

[ ] //trenary operator
int a=12;int b=8;int min=0; boolean bb=true;
if (a<b) min=a;
else min=b;

System.out.println(min);

[ ] min = (a<b) ? a : b;
System.out.println(min);

[ ] int c = 10; int max=0;


/*if (a>b) { if (a>c) max=a;
else max=c;}
else { if (b>c) max=b;
else max=c;}*/

max = (a>b) ? ((a>c)? a:c) : ((b>c)? b:c);


System.out.println(max);

[ ] int income=50000;
double rate = 0.35;
if (income < 311950) rate = 0.33;
if (income < 174700) rate = 0.28;
if (income < 114650) rate = 0.25;
if (income < 47450) rate = 0.22;
System.out.println(rate);

[ ] //Is a given year a leap year?


//A. Yes if its century and divisible by 400 otherwise divisible by 4
//i.e if either (i) divisible by 400 or (ii) divisible by 4 but not 100

[ ] //leap year using ternary operator

int year = 2006; boolean b;

b = (year%100==0) ? ((year%400==0)?true:false):((year%4==0)? true:false);


System.out.println(b)

[ ] //A. Yes if its century and divisible by 400 otherwise divisible by 4


//i.e if either (i) divisible by 400 or (ii) divisible by 4 but not 100
//Java progam using logical operator and mod.

int year = 2000;


//boolean b = (year%400==0)||(year%4==0 && year%100 != 0);
//System.out.println(b);
//b= ((year%400==0)||(year%4==0 && year%100 != 0)) ? true: false;
//b = (year%100==0)? ((year%400==0)? true:false) : ((year%4==0)?true:fal
System.out.println(b);
int i=0;
if (i==5) b=true;
else b=false;

Iterations - for, while, do-while

For loop
for(initialize;loop continuation; loop condition update) {
statement 1;
statement 2;
statement 3;
.....
}

1. initialize
2. check loop continuation condition,
3. if true, do  
    3.1 statement 1;
    3.2 statement 2;
    3.3 statement 3;
4 loop condition update
5. Go back to 2

[ ] int i=1;
for (;;) {
if (i>8){ break;} // i<=8
System.out.print(i+" ");
i++;
}

[ ] int sum=0; int i=0;


for (i=0, sum=0;i<10 ;sum+=i,i++ )
System.out.println(sum);

[ ] int f = 0, g = 1;
for (int i = 0; i <= 5; i++)
{ System.out.print(f+" ");
// i = 0 1 2 3 4 5
f = f + g; // f = 0 1 1 2 3 5 8
g = f - g; // g = 1 0 1 1 2 3 5
}
// 0 1 1 2 3 5 8 //fibonnaci

[3] public static final int END = Integer.MAX_VALUE; // 2147483647


public static final int START = END - 100;
System.out.println(START);
int count =0;
for(long i=START; i <= END ;i++) { count ++;
} //for
System.out.println(count);
//System.out.println(++i);

2147483547
102

[5] int i=0; int j=5;


for (; (i < 4) && (j++ < 10); i++)
System.out.print(" "+i+" "+j);
System.out.println(" "+i+" "+j);

// 0 6 1 7 2 8 3 8

0 6 1 7 2 8 3 9 4 9

while and do while


while (some condition is true) {
do something
}

[7] int i=1;


while (i<9) {
System.out.print(i+" ");
i++;
}

1 2 3 4 5 6 7 8

[ ] do { 1. add
2. sub
3. multiply
4. divide
5. exit

} while (option != exit)

[ ] //Check a given number if prime or not?


//A prime number is one that is divisible only by 1 and itself.
int num = 23; boolean prime = true;

System.out.println(prime);

[9] // count the digits of a given number


int num=564398; // 5+6+4+3+8
int sum=0;
//int count=0;
while(num!=0) { // for (;num!=0;num=num/10) {sum +=num%10}
// int i = num%10;
sum += num%10;
num = num/10;
}

System.out.println(sum);

35

[1] for (int i = 1; i <= 3; i++) {


System.out.println("i = " + i);
for (int j = 1; j <= 5; j++) {
System.out.print(" j = " + j);
}
System.out.println();
}
i = 1
j = 1 j = 2 j = 3 j = 4 j = 5
i = 2
j = 1 j = 2 j = 3 j = 4 j = 5
i = 3
j = 1 j = 2 j = 3 j = 4 j = 5

Write a program that takes a command-line argument N and prints a N row


pattern like the one below

I. *
  **
  ***
  ****
  *****
 
II.
  *****
    ****
    ***
      **
      *
 

[6] int N=5;

for (int i = 1; i <=N; i++) {


for (int j = 1; j <i; j++)
System.out.print(" ");
for (int j = i; j <=N; j++)
System.out.print("*");

System.out.println();
}

*****
****
***
**
*

II. Write a program that takes a command-line argument N and prints a


(2N + 1)-by-(2N + 1) ex like the one below

  *...*
  .*.*.
  ..*..
  .*.*.
  *...*
   
   
   

[10] int n=2;


/*
-2-1 0 1 2
-1
0
1
2
*/
for (int i=-n; i<=n;i++) {
for (int j=-n;j<=n;j++) {
if ((i==j) || (i==-j)) System.out.print("*");
else System.out.print(".");
}
System.out.println();
}

*...*
.*.*.
..*..
.*.*.
*...*

[7] // n=2. Therefore 5x5


int N=2; // need 5x5 pattern
for (int i = 1; i <=(2*N+1); i++) {
for (int j = 1; j <=(2*N+1); j++)
if (i==j) System.out.print("*");
else if (i+j==(2*N+2)) System.out.print("*");
else System.out.print(".");

System.out.println();
}

*...*
.*.*.
..*..
.*.*.
*...*

[ ] Scanner in = new Scanner (System.in);


int a,b,c=0;
for (int i=0;i<10;i++) { System.out.println ("enter 2 numbers:"); a= in.n
b= in.nextInt();
if ( b==0) {System.out.println("Denominator cant be zero");
continue;
}
c= a/b; System.out.println(c);
}

Strings
String is a sequence of Unicode characters
• The String class belongs to the java.lang package, which does not require an import
statement
• A string literal is a sequence of characters between double quotes
doesn’t have to be constructed
can be passed to methods and constructors as parameters
• There is no primitive type for representing strings in Java
• In Java, ordinary strings are objects of the class String
• String that has zero character is called an empty String “”
• Unlike other classes, String has two operators, + and += (usedfor concatenation)

[13] String s = new String("abc"); // 250


String s1="abc"; // 200 in heap
String s3 = new String("abc"); //350
String s2 = "abc"; // 200 in heap
System.out.println(s==s3);

false

Strings are Immutable


• Once a String object is created, it can never be changed
• Immutable objects are convenient because several references can point to the same object
safely: there is no danger of changing an object through one reference without the others
being aware of the change.

Special Characters
• Strings can include special characters by providing escape sequences
• \u / a Unicode character /
• \b / \u0008: backspace BS /
• \t / \u0009: horizontal tab HT /
• \n / \u000a: linefeed LF /
• \f / \u000c: form feed FF /
• \r / \u000d: carriage return CR /
• \" / \u0022: double quote " /
• \' / \u0027: single quote ' /
• \ / \u005c: backslash \ /

[18] String s=""; // 500 "a"


String s1 = new String("a"); // creats a memorly location to hold the o
String s2 = "a"; // search literal pool for "a" if found pick that
String s3 = new String("a"); // 650 "a"
String s4 ="a\tc";
//System.out.println(s);
//s+=27;
System.out.print(s.length());

[13] //charAt, length, indexOf(), lastIndexOf()


//500 = "abcdefabcdennbb"
//s will contain 500

String s ="abcdefabcdennbb"; // 500 s=500 500 +i


// 01234567
System.out.println(s.length());
System.out.println(s.charAt(2));

int count=0; int i=0; int j=0;


while ((j=s.indexOf("b",i))!=-1){
count++;
i=++j;
}
//System.out.println(count);

//s.indexOf("z",0);
s.lastIndexOf("b",6);
//s1.equalsIgnoreCase(s3);

15
c

[7] // substring , contains, equals,compareTo, split // compareTo lexic


// conversion parseint/tostring
// wrapper class
//Integer.toString(i).length()
String s= "Today is Thursday";
int i=2;
s.substring(i,i+1);
//s.charAt(i);

s.contains("day");
String s1 ="GaneshMo";
String s3= "Ganeshmo";
s1.compareTo(s3); // + s1 > s3 -ve s1 < s3 0 s1 = s3
s1.equalsIgnoreCase(s3);
String [] st = s.split("y");
System.out.println(Arrays.toString(st));
[Toda, is Thursda]

[38] // palindrome check


// madam - reverse is also madam is a palindrome
// Ganesh - reverse is hsenaG not a palindrome
String s = "madam";
boolean palin=true; String s1="";
/*for (int i=s.length()-1; i>=0;i--) {
s1 = s1+s.charAt(i);
} */
for (int i=0; i< s.length()/2;i++) {
if (s.charAt(i)!=s.charAt(s.length()-1-i)) {palin=false;break;}
}
//palin = s.equalsIgnoreCase(s1);
System.out.println(s+" is palindrome : "+palin);

madam is palindrome : true

[40] // count vowels in a given string


String s = "All day is holiday " ; // vowels = 6
int count=0;
int i=0;
String vowels = "aeiouAEIOU";
for(i=0; i<s.length();i++) {
String ch = s.substring(i,i+1);
if (vowels.contains(ch)) count++;
}
System.out.println(count);
//String [] a = s.split(" ");
//System.out.print(Arrays.toString(a));

[ ] // count words in a given string


// "aaaaaaaa" "aa"
String s = "Today is Monday and not Sunday hi";
int count=0; int i=0;
String search = "day"; // ans = 3
String [] a = s.split("day");
/*while ((j=s.indexOf(search,i))!=-1){
count++;
i=++j;
} */
System.out.println(a.length);
[44] // diff between name.equals("Ganesh") vs "Ganesh".equals(name);
String name="";
//="ganesh";

System.out.println(name.equals("ganesh"));
System.out.println("ganesh".equals(name));

false
false

StringBuilder

A StrinBuilder has a capacity(the number of chracters it can hold) and a


length (the number of characters it is currently holdng)

If the capacity is exceeded, stringBuilder is expanded.

StringBuilder is a reimplentation of StringBuffer

Constructors -
      StringBuilder() - empty stringbuilder builds with a capacity of
16
      StringBuilder(int capacity) - builds with a given capacity
      StringBuilder(String S)     - builds with a capacity of length of
S + 16

[47] String s = "This is a StringBuilder";


System.out.println("l="+s.length());
StringBuilder sb = new StringBuilder(s);
System.out.println(sb.capacity());
sb.append("Hi How are you??#");
//sb.setLength(42);
System.out.println(sb.length()+" "+sb.capacity());
System.out.println(sb);
/*
sb.insert(2,"!#");
sb.setCharAt(2,'#');
//System.out.println(sb);
//sb.reverse();
System.out.println(sb.capacity());
System.out.println(sb);
System.out.println(sb.reverse()); */

l=23
39
40 80
This is a StringBuilderHi How are you??#

methods of StringBuilder

[ ] apart from length(), charAt(), subString() stringBuilder has its own meth

setLength() - sets the length of the string, this may result in truncatio

reverse() - the characters in the string are replaced with the characte

Other methods to edit are:

insert(int offset, X) - inserts X starting at the location offset and al


and will be converted to string and inserted.

deleteCharAt(int index) - deletes the character at the index position

setCharAt (int index, char ch) - replaces the character at index postio

delete (int start, int end) - will delete string of characters from s

[3] // palindrome check


// madam - reverse is also madam is a palindrome
// Ganesh - reverse is hsenaG not a palindrome
String s = "madam";
StringBuilder sbr= new StringBuilder(s);
String s1 = sbr.reverse().toString();(
s.equals(s1);

true

[4] // palindrome check


// madam - reverse is also madam is a palindrome
// Ganesh - reverse is hsenaG not a palindrome
String s = "Madam";
//StringBuilder sb = new StringBuilder(s);
//String s1 = sb.reverse().toString();
s.equalsIgnoreCase(new StringBuilder(s).reverse().toString());

true
StringTokenizer

StringTokenizer is part of java.util. package

It is a trivial tokenizer. Everything is either a token or a delimiter

Constructors :

StringTokenizer(String str) - whitespace is the delimiter. Any sequence of non-white


space is returned as tokens
StringTokenizer(String str, string delim) - instead of whitespace each character in the
delim string is the delimiter
StringTokenizer(String str, string delim, boolem returnDelim) - by default delimter is
stripped from the token returned, if you want the delimter then set the third parameter
as true

[13] String s = new String("Today is wednesday. Is it raining? What a nice wea


StringTokenizer st = new StringTokenizer(s);
System.out.println(st.countTokens());
System.out.println(st.nextToken());
System.out.println(st.nextToken());
System.out.println(st.nextToken());
//System.out.println(st.nextToken());
System.out.println(st.countTokens());

10
Today
is
wednesday.
7

methods of StringTokenizer

[ ] The following methods are available in stringTokenizer

int countTokens() - returns the number of tokens in the string based on


boolean hasMoreTokens() - returns true if there are more tokens availab
string nextToken() - returns the next available token

[11] StringTokenizer st = new StringTokenizer("Today is working day. It is no

while (st.hasMoreTokens()) {
String s = st.nextToken();
String delim = st.nextToken();
StringTokenizer st1 = new StringTokenizer(s);
if (delim.equals(".")) while (st1.hasMoreTokens()) {System.out.pr
if (delim.equals("?")) while (st1.hasMoreTokens()) {System.out.pr
if ("!".equals(delim)) while (st1.hasMoreTokens()) {System.out.pr
// if (!delim.equals("!")) while (st1.hasMoreTokens()) {System.out
System.out.println();
}

Today,is,working,day,
It#is#not#a#holiday#
Its@a@nice@weather@

[16] StringTokenizer st = new StringTokenizer("Today is working day not a hol


int size = st.countTokens();
for (int i=0; i<size;i++) {
System.out.println(st.nextToken()); // day not a holiday
System.out.println("i="+i+" "+st.countTokens());
}

Today
i=0 6
is
i=1 5
working
i=2 4
day
i=3 3
not
i=4 2
a
i=5 1
holiday
i=6 0

[21] String s= "abcde789efg9765uyxt123";


StringTokenizer st = new StringTokenizer(s,"abcdefghijklmnopqrstuvwxyz");
st.nextToken();
st.nextToken();
st.nextToken();

123

[24] // find the sum of the numbers from the text "abcde789efg9765uyxt123"
String s= "34abcde789efg9765uyxt123"; // 789+9765+123 =
/*String n = "0123456789"; String num=""; int sum=0;
for (int i=0; i<s.length();i++) {
char ch = s.charAt(i);
if (n.contains(ch+"")) {num+=ch;}
else { if (num !="")
{sum += Integer.parseInt(num); num="";}
}
}
if (num !="")
{sum += Integer.parseInt(num); num="";} */

StringTokenizer st = new StringTokenizer(s,"abcdefghijklmnopqrsuvwxyz");


//int [] arr = new int[st.countTokens()];
int sum=0;
while(st.hasMoreTokens()) {
sum += Integer.parseInt(st.nextToken());
}

System.out.println(sum);

--------------------------------------------------------------------------
-
java.lang.NumberFormatException: For input string: "t123"
at
java.base/java.lang.NumberFormatException.forInputString(NumberFormatExcep
tion.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at .(#72:1)

[ ]

[ ]

[ ] // find the sum of the numbers from the text "abcde789efg9765uyxt123"


String s= "abcde100wxyz1000abcde123"; // 789+9765+123
String [] a = s.split("/w");
StringTokenizer st = new StringTokenizer(s,"abcdefghijklmnopqrstuvwxyz")
int size = st.countTokens(); int sum=0;
for (int i=0; i<size;i++) {
sum +=Integer.parseInt(st.nextToken());
}
System.out.println(Arrays.toString(a)+" "+sum);

You might also like