03 Java Language Basics Pr
03 Java Language Basics Pr
STRUCTURE
10/15/2024 MUNYAO 1
JAVA PROGRAM BASICS
• Just like other programming languages Java has features
such as; variables, operators, expressions, statements,
arrays, strings and control flow statements.
• Variables
• A variable is the name of a particular memory location
that stores a specific type of data. Each variable has a
type, such as int or Object, and a scope. You must
explicitly provide a name and a type for each variable you
want to use in your program in the form shown below:
10/15/2024 MUNYAO 2
keywords
abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while
10/15/2024 MUNYAO 3
import java.util.Scanner; .
public class Essentials
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int value1 = 0;
System.out.println("Enter a number:");
value1 = in.nextInt();
int value2 = 0;
System.out.println("Enter a second number:");
value2 = in.nextInt();
int sum;
sum = value1 + value2;
System.out.println("Sum = " + sum);
}
} MUNYAO 4
import java.util.Scanner;
public class Registration .
{public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String regno;
System.out.println("Enter Registration Number:");
regno = in.next();
String firstName;System.out.println("Enter Student
First Name:");
firstName = in.next();
System.out.println("Student Registration Number is : "
+ regno);
System.out.println("Student First Name is : " + 5
firstName); }}
Example:
• A program refers to a variable's value by the variable's
name. A simple name is composed of a single identifier.
The following must hold true for a simple name:
• It must begin with a letter.
• It must not be a keyword.
• It must be unique within its scope.
• By Convention: Variable names begin with a lowercase
letter, and class names begin with an uppercase letter. If a
variable name consists of more than one word, the words are
joined together, and each word after the first begins with an
uppercase letter. The underscore character (_) is acceptable
anywhere in a name, but by convention is used only to
10/15/2024 MUNYAO 6
separate words in constants
DATA TYPES
Keyword Description Size/Format
Integers
byte Byte-length integer 8-bit [-128 to 127]
short Short integer 16-bit two's complement
int Integer 32-bit two's complement
long Long integer 64-bit two's complement
10/15/2024 MUNYAO 7
32-bit [big numbers with
float Single-precision floating point
decimal points]
64-bit [very big numbers
double Double-precision floating point
with decimal points]
Other types
char A single character 16-bit Unicode character
boolean A boolean value (true or false) True or false
10/15/2024 MUNYAO 9
Variable Initialization
Local variables and member variables can be initialized with an
assignment statement when they're declared. The data type of the
variable must match the data type of the value assigned to it.
Initializing Final Variables
A final variable is one whose value does not change after it has been
initialized (usually referred to as a constant in other programming
languages).
To declare a final variable, use the final keyword in the variable
declaration before the type:
Example
final int aFinalVar = 0;
final double PI = 3.14159; // Declare a constant
10/15/2024 MUNYAO 10
Operators
Operators are used to perform operations on variables and
values.
In the example below, we use the + operator to add together
two values
Operators are symbols used to manipulate values,i.e, they
operate on values.In java operators can be grouped into:
• Arithmetic Operators
• Relational and Conditional Operators
• Shift and Logical Operators
• Assignment Operators
10/15/2024 MUNYAO 11
Expressions, Statements, and
Blocks
• Literals, variables, and operators are combined to form
expressions. Certain expressions can be made into
statements. By grouping statements together with curly
braces {and}, you create blocks of code.
• 3.6.1 Expressions
• An expression is a series of variables, operators, and
method calls (constructed according to the syntax of the
language) that evaluates to a single value. When making
compound expressions (Example x+y/100) it is important
to consider the operator precedence.
10/15/2024 MUNYAO 12
Blocks
• A block is a group of zero or more statements between
balanced /curly braces and can be used anywhere a single
statement is allowed.
10/15/2024 MUNYAO 13
Example
import java.util.Scanner;
public class FahrenheitToCelcius {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double fahrenheit; // Say 100;
System.out.println("Enter a number:");
fahrenheit = in.nextInt();
double celsius = (5.0 / 9) * (fahrenheit - 32);
System.out.println("Fahrenheit " + fahrenheit + " is "
+celsius + " in Celsius");
}
}
10/15/2024 MUNYAO 14
Numbers – data types
• All the wrapper classes (Integer, Long, Byte, Double,
Float, Short) are subclasses of the abstract class Number.
10/15/2024 MUNYAO 15
Number Methods:
SN Methods with Description
1 xxxValue() Converts the value of this Number object
to the xxx data type and returned it.
2 compareTo() Compares this Number object to the
argument.
3 equals() Determines whether this number object is
equal to the argument.
4 valueOf() Returns an Integer object holding the value
of the specified primitive.
5 toString() Returns a String object representing the
value of specified int or Integer.
6 parseInt() This method is used to get the primitive
data type of a certain String.
10/15/2024 MUNYAO 16
Number Methods:
SN Methods with Description
7 abs() Returns the absolute value of the argument.
8 ceil() Returns the smallest integer that is greater than
or equal to the argument. Returned as a double.
9 floor() Returns the largest integer that is less than or
equal to the argument. Returned as a double.
10 rint() Returns the integer that is closest in value to the
argument. Returned as a double.
11 round() Returns the closest long or int, as indicated
by the method's return type, to the argument.
12 min() Returns the smaller of the two arguments.
10/15/2024 MUNYAO 17
Number Methods:
SN Methods with Description
10/15/2024 MUNYAO 18
public class Test{ .
public static void main(String args[]){
Integer x =5; // Returns byte primitive data
type System.out.println( x.byteValue());
// Returns double primitive data type
System.out.println(x.doubleValue());
// Returns long primitive data type
System.out.println( x.longValue());
}
}
10/15/2024 MUNYAO 19
example
import java.util.Scanner;
public class IntegerFunction {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int value1 = 0;
System.out.println("Enter a number:");
value1 = in.nextInt();
int value2 = 0;
System.out.println("Enter a second number:");
value2 = in.nextInt();
int sum;
sum = value1 + value2;
System.out.println("The Sum = " + sum);
System.out.println("\n The highest number of the two is " + Math.max(value1, value2));
System.out.println("\n The lowest number of the two is " + Math.min(value1, value2));
System.out.println("\n The square of the first number is " + Math.pow(value1, 2));
}
}
10/15/2024 MUNYAO 20
compareTo() - Return Value:
If the Integer is equal to the argument then 0 is returned.
If the Integer is less than the argument then -1 is returned.
If the Integer is greater than the argument then 1 is
returned.
public class Test{ public static void main(String args[]){
Integer x =5;
System.out.println(x.compareTo(3));
System.out.println(x.compareTo(5));
System.out.println(x.compareTo(8)); } }
Output 1 0 -1
10/15/2024 MUNYAO 21
public class Absolute {
public static void main(String args[]){
Integer a =-8;
double d =-100;
float f =-90;
System.out.println(Math.abs(a));
System.out.println(Math.abs(d));
System.out.println(Math.abs(f));
}
}
10/15/2024 MUNYAO 22
rint()
public class TestRint{
public static void main(String args[]){
double d =100.675; double e =100.500; double f =100.200;
System.out.println(Math.rint(d));
System.out.println(Math.rint(e));
System.out.println(Math.rint(f)); } }
101.0 100.0 100.0
10/15/2024 MUNYAO 23
Random()
public class TestRand {
public static void main(String args[]){
long p= Math.round(10000*Math.random());
long t= Math.round(10000*Math.random());
System.out.println("Your password is = "+p);
System.out.println("Your password is = "+t);
}
}
10/15/2024 MUNYAO 24
Java Characters / String
• A String is an object that contains a sequence of
characters.
• Declaring and instantiating a String is much like any
other object variable.
• However, there are differences: They can be instantiated
(created) without using the new keyword.
• They are immutable.
• Once instantiated, they are final and cannot be changed.
• char ch ='a';
• // an array of chars
• char[] charArray ={'a','b','c','d','e'};
10/15/2024 MUNYAO 25
String operations
public class StringOperations{
public static void main(String[] args){
String string1 = "Hello";
String string2 = "Caron";
String string3 = ""; //empty String or null
string3 = "How are you "+ string2.concat(string1);
System.out.println("string3: "+ string3); //get length
System.out.println("Length: "+ string1.length());
//get substring beginning with character 0, up to, but not
//including character 5
System.out.println("Sub: "+ string3.substring(0,5)); //uppercase
System.out.println("Upper: "+string3.toUpperCase()); } }
10/15/2024 26
import java.util.Scanner;
example
public class StringOperations{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String fName;
System.out.println("Enter your First Name :");
fName = scan.next();
String lName;
System.out.println("Enter your Last Name:");
lName = scan.next();
System.out.println("How are You "+ fName+" "+lName);
System.out.println("Length: "+ fName.length()); //get substring beginning with
//character 0, up to, but not //including character 2
System.out.println("Sub: "+ fName.substring(0,2)); //uppercase
System.out.println("Name in Upper case: "+fName.toUpperCase());
System.out.println("Name in lowe case: "+fName.toLowerCase());
}}
10/15/2024 MUNYAO 27
Escape Description
Sequence
\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\' Inserts a single quote character in the text at this
point.
\" Inserts a double quote character in the text at
this point.
10/15/2024 MUNYAO 28
Character Methods:
Methods with Description
isLetter() Determines whether the specified char value is a
letter.
isDigit() Determines whether the specified char value is a
digit.
isWhitespace() Determines whether the specified char value is
white space.
isUpperCase() Determines whether the specified char value is
uppercase.
isLowerCase() Determines whether the specified char value is
lowercase.
toUpperCase() Returns the uppercase form of the specified char
value.
toLowerCase() Returns the lowercase form of the specified char
value.
toString() Returns a String object representing the specified
character valuethat is, a one-character string.
isLetter()
public class TestLetter{
public static void main(String args[]){
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5')); }
}
Result
true
false
10/15/2024 MUNYAO 30
isDigit()
public class Test{
public static void main(String args[]){
System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('5')); } }
Result
False
true
10/15/2024 MUNYAO 31
isWhitespace()
public class Test{
public static void main(String args[]){
System.out.println(Character.isWhitespace('c'));
System.out.println(Character.isWhitespace(' '));
System.out.println(Character.isWhitespace('\n'));
System.out.println(Character.isWhitespace('\t')); } }
False
true
true
true
10/15/2024 MUNYAO 32
String Length:
public class StringDemo{
public static void main(String args[]){
String p ="Dot saw I was Tod";
int len = p.length();
System.out.println("String Length is : "+ len ); }
}
10/15/2024 MUNYAO 33
String Methods:
Methods Description
char charAt(int index) Returns the character at the specified index.
int compareTo(String Compares two strings lexicographically.
anotherString)
String concat(String str) Concatenates the specified string to the end of this
string.
int length() Returns the length of this string.
String replace(char Returns a new string resulting from replacing all
oldChar, char newChar) occurrences of oldChar in this string with newChar.
String replace(char Returns a new string resulting from replacing all
oldChar, char newChar) occurrences of oldChar in this string with newChar.
boolean startsWith(String Tests if this string starts with the specified prefix.
prefix)
CharSequence Returns a new character sequence that is a
subSequence(int subsequence of this sequence.
beginIndex, int endIndex)
String substring(int Returns a new string that is a substring of this string.
beginIndex)
String substring(int Returns a new string that is a substring of this string.
beginIndex, int endIndex)
String Methods:
Methods Description
String toLowerCase() Converts all of the characters in this String to
lower case using the rules of the default locale.
String toUpperCase() Converts all of the characters in this String to
upper case using the rules of the default locale.
String trim() Returns a copy of the string, with leading and
trailing whitespace omitted.
10/15/2024 MUNYAO 35
public class Test{
public static void main(String args[]){
String s ="Strings are immutable";
char result = s.charAt(8);
System.out.println(result); } }
10/15/2024 MUNYAO 36
public class Test{
public static void main(String args[]){
String str1 ="Strings are immutable";
String str2 ="Strings are immutable";
String str3 ="Integers are not immutable";
int result = str1.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);
result = str3.compareTo( str1 );
System.out.println(result); }
}
Results 0 10 -10
10/15/2024 MUNYAO 37
import java.io.*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :");
System.out.println(Str.replace('o','T'));
System.out.print("Return Value :");
System.out.println(Str.replace('l','D')); } }
10/15/2024 MUNYAO 38
public class Test{ public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :");
System.out.println(Str.startsWith("Welcome"));
System.out.print("Return Value :");
System.out.println(Str.startsWith("Tutorials"));
System.out.print("Return Value :");
System.out.println(Str.startsWith("Tutorials",11)); } }
10/15/2024 MUNYAO 40
import java.io.*;
public class Test{
public static void main(String args[]){
String Str=new String(" Welcome to Tutorialspoint.com ");
System.out.print("Return Value :");
System.out.println(Str.trim()); } }
10/15/2024 MUNYAO 41
Determining Leap Year
A year is a leap year if it is divisible by 4 but not by 100 or if it is divisible by 400.
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
import javax.swing.JOptionPane;
public class LeapYear{
public static void main(String args[]) {
// Prompt the user to enter a year
String yearString = JOptionPane.showInputDialog("Enter a year");
// Convert the string into an int value
int year = Integer.parseInt(yearString);
// Check if the year is a leap year
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year %
400 == 0);
// Display the result in a message dialog box
JOptionPane.showMessageDialog(null, year + " is a leap year? " +
isLeapYear);
} }
10/15/2024 MUNYAO 42
END
10/15/2024 MUNYAO 43
10/15/2024 MUNYAO 44
10/15/2024 MUNYAO 45